<commit_before>/*
 * Copyright (c) 2011-Present VMware, Inc. or its affiliates, All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package reactor.netty.http.client;

import io.netty.handler.codec.http.HttpResponseStatus;
import java.security.cert.CertificateException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.util.ReferenceCountUtil;
import org.apache.commons.lang3.StringUtils;
import org.junit.Ignore;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.netty.DisposableServer;
import reactor.netty.SocketUtils;
import reactor.netty.http.server.HttpServer;
import reactor.netty.resources.ConnectionProvider;
import reactor.test.StepVerifier;
import reactor.util.function.Tuple2;

import static org.assertj.core.api.Assertions.assertThat;

public class HttpRedirectTest {

	@Test
	@Ignore
	public void deadlockWhenRedirectsToSameUrl(){
		redirectTests("/login");
	}

	@Test
	@Ignore
	public void okWhenRedirectsToOther(){
		redirectTests("/other");
	}

	private void redirectTests(String url) {
		AtomicInteger counter = new AtomicInteger(1);
		DisposableServer server =
				HttpServer.create()
				          .port(0)
				          .handle((req, res) -> {
				              if (req.uri().contains("/login") &&
				                      req.method().equals(HttpMethod.POST) &&
				                      counter.getAndDecrement() > 0) {
				                  return res.sendRedirect(url);
				              }
				              else {
				                  return res.status(200)
				                            .send();
				              }
				          })
				          .wiretap(true)
				          .bindNow();

		ConnectionProvider pool = ConnectionProvider.create("redirectTests", 1);

		HttpClient client =
				HttpClient.create(pool)
				          .addressSupplier(server::address);

		try {
			Flux.range(0, 1000)
			    .concatMap(i -> client.followRedirect(true)
			                          .post()
			                          .uri("/login")
			                          .responseContent()
			                          .then())
			    .blockLast(Duration.ofSeconds(30));
		}
		finally {
			server.disposeNow();
		}

	}

	@Test
	public void redirectDisabledByDefault() {
		DisposableServer server =
				HttpServer.create()
				          .port(0)
				          .host("localhost")
				          .wiretap(true)
				          .route(r -> r.get("/1", (req, res) -> res.sendRedirect("/3"))
				                       .get("/3", (req, res) -> res.status(200)
				                                                   .sendString(Mono.just("OK"))))
				          .wiretap(true)
				          .bindNow();

		HttpClientResponse response =
				HttpClient.create()
				          .addressSupplier(server::address)
				          .wiretap(true)
				          .get()
				          .uri("/1")
				          .response()
				          .block(Duration.ofSeconds(30));

		assertThat(response).isNotNull();
		assertThat(response.status()).isEqualTo(HttpResponseStatus.FOUND);
		assertThat(response.responseHeaders().get("location")).isEqualTo("/3");

		server.disposeNow();
	}

	/** This ensures functionality such as metrics and tracing can accurately count requests. */
	@Test
	public void redirect_issuesOnRequestForEachAttempt() {
		DisposableServer server =
				HttpServer.create()
				          .port(0)
				          .host("localhost")
				          .wiretap(true)
				          .route(r -> r.get("/1", (req, res) -> res.sendRedirect("/3"))
				                       .get("/3", (req, res) -> res.status(200)
				                                                   .sendString(Mono.just("OK"))))
				          .bindNow();

		AtomicInteger onRequestCount = new AtomicInteger();
		AtomicInteger onResponseCount = new AtomicInteger();
		AtomicInteger onRedirectCount = new AtomicInteger();
		AtomicInteger doOnResponseError = new AtomicInteger();
		Tuple2<String, HttpResponseStatus> response =
				HttpClient.create()
				          .addressSupplier(server::address)
				          .wiretap(true)
				          .followRedirect(true)
				          .doOnRequest((r, c) -> onRequestCount.incrementAndGet())
				          .doOnResponse((r, c) -> onResponseCount.incrementAndGet())
				          .doOnRedirect((r, c) -> onRedirectCount.incrementAndGet())
				          .doOnResponseError((r, t) -> doOnResponseError.incrementAndGet())
				          .get()
				          .uri("/1")
				          .responseSingle((res, bytes) -> bytes.asString().zipWith(Mono.just(res.status())))
				          .block(Duration.ofSeconds(30));

		assertThat(response).isNotNull();
		assertThat(response.getT1()).isEqualTo("OK");
		assertThat(response.getT2()).isEqualTo(HttpResponseStatus.OK);
		assertThat(onRequestCount.get()).isEqualTo(2);
		assertThat(onResponseCount.get()).isEqualTo(1);
		assertThat(onRedirectCount.get()).isEqualTo(1);
		assertThat(doOnResponseError.get()).isEqualTo(0);

		server.disposeNow();
	}

	@Test
	public void testIssue253() {
		final int serverPort1 = SocketUtils.findAvailableTcpPort();

		DisposableServer server =
				HttpServer.create()
				          .port(serverPort1)
				          .host("localhost")
				          .wiretap(true)
				          .route(r -> r.get("/1",
				                                   (req, res) -> res.sendRedirect("http://localhost:" + serverPort1 + "/3"))
				                       .get("/2",
				                                   (req, res) -> res.status(301)
				                                                    .header(HttpHeaderNames.LOCATION, "http://localhost:" + serverPort1 + "/3")<commit_msg>Adds failing test for unexpected timing in `HttpClient.doOnResponse()` (#1033)<commit_after>/*
 * Copyright (c) 2011-Present VMware, Inc. or its affiliates, All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package reactor.netty.http.client;

import io.netty.handler.codec.http.HttpResponseStatus;
import java.security.cert.CertificateException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.util.ReferenceCountUtil;
import org.apache.commons.lang3.StringUtils;
import org.junit.Ignore;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.netty.DisposableServer;
import reactor.netty.SocketUtils;
import reactor.netty.http.server.HttpServer;
import reactor.netty.resources.ConnectionProvider;
import reactor.test.StepVerifier;
import reactor.util.function.Tuple2;

import static org.assertj.core.api.Assertions.assertThat;

public class HttpRedirectTest {

	@Test
	@Ignore
	public void deadlockWhenRedirectsToSameUrl(){
		redirectTests("/login");
	}

	@Test
	@Ignore
	public void okWhenRedirectsToOther(){
		redirectTests("/other");
	}

	private void redirectTests(String url) {
		AtomicInteger counter = new AtomicInteger(1);
		DisposableServer server =
				HttpServer.create()
				          .port(0)
				          .handle((req, res) -> {
				              if (req.uri().contains("/login") &&
				                      req.method().equals(HttpMethod.POST) &&
				                      counter.getAndDecrement() > 0) {
				                  return res.sendRedirect(url);
				              }
				              else {
				                  return res.status(200)
				                            .send();
				              }
				          })
				          .wiretap(true)
				          .bindNow();

		ConnectionProvider pool = ConnectionProvider.create("redirectTests", 1);

		HttpClient client =
				HttpClient.create(pool)
				          .addressSupplier(server::address);

		try {
			Flux.range(0, 1000)
			    .concatMap(i -> client.followRedirect(true)
			                          .post()
			                          .uri("/login")
			                          .responseContent()
			                          .then())
			    .blockLast(Duration.ofSeconds(30));
		}
		finally {
			server.disposeNow();
		}

	}

	@Test
	public void redirectDisabledByDefault() {
		DisposableServer server =
				HttpServer.create()
				          .port(0)
				          .host("localhost")
				          .wiretap(true)
				          .route(r -> r.get("/1", (req, res) -> res.sendRedirect("/3"))
				                       .get("/3", (req, res) -> res.status(200)
				                                                   .sendString(Mono.just("OK"))))
				          .wiretap(true)
				          .bindNow();

		HttpClientResponse response =
				HttpClient.create()
				          .addressSupplier(server::address)
				          .wiretap(true)
				          .get()
				          .uri("/1")
				          .response()
				          .block(Duration.ofSeconds(30));

		assertThat(response).isNotNull();
		assertThat(response.status()).isEqualTo(HttpResponseStatus.FOUND);
		assertThat(response.responseHeaders().get("location")).isEqualTo("/3");

		server.disposeNow();
	}

	/** This ensures functionality such as metrics and tracing can accurately count requests. */
	@Test
	public void redirect_issuesOnRequestForEachAttempt() {
		DisposableServer server =
				HttpServer.create()
				          .port(0)
				          .host("localhost")
				          .wiretap(true)
				          .route(r -> r.get("/1", (req, res) -> res.sendRedirect("/3"))
				                       .get("/3", (req, res) -> res.status(200)
				                                                   .sendString(Mono.just("OK"))))
				          .bindNow();

		AtomicInteger onRequestCount = new AtomicInteger();
		AtomicInteger onResponseCount = new AtomicInteger();
		AtomicInteger onRedirectCount = new AtomicInteger();
		AtomicInteger doOnResponseError = new AtomicInteger();
		Tuple2<String, HttpResponseStatus> response =
				HttpClient.create()
				          .addressSupplier(server::address)
				          .wiretap(true)
				          .followRedirect(true)
				          .doOnRequest((r, c) -> onRequestCount.incrementAndGet())
				          .doOnResponse((r, c) -> onResponseCount.incrementAndGet())
				          .doOnRedirect((r, c) -> onRedirectCount.incrementAndGet())
				          .doOnResponseError((r, t) -> doOnResponseError.incrementAndGet())
				          .get()
				          .uri("/1")
				          .responseSingle((res, bytes) -> bytes.asString().zipWith(Mono.just(res.status())))
				          .block(Duration.ofSeconds(30));

		assertThat(response).isNotNull();
		assertThat(response.getT1()).isEqualTo("OK");
		assertThat(response.getT2()).isEqualTo(HttpResponseStatus.OK);
		assertThat(onRequestCount.get()).isEqualTo(2);
		assertThat(onResponseCount.get()).isEqualTo(1);
		assertThat(onRedirectCount.get()).isEqualTo(1);
		assertThat(doOnResponseError.get()).isEqualTo(0);

		server.disposeNow();
	}


	/**
	 * This ensures metrics and tracing get reliable timing. {@link HttpClient#doOnResponse} should
	 * return when headers are received. Blocking client usage should therefore finish after that
	 * timestamp.
	 */
	@Test
	public void redirect_onResponseBeforeBlockCompletes() throws Exception {
		DisposableServer server =
				HttpServer.create()
						.port(0)
						.host("localhost")
						.wiretap(true)
						.route(r -> r.get("/1", (req, res) -> res.sendRedirect("/3"))
								.get("/3", (req, res) -> res.status(200)
										.sendString(Mono.just("OK"))))
						.bindNow();

		BlockingQueue<Long> doOnResponseNanos = new LinkedBlockingQueue<>();
		Long responseNanos =
				HttpClient.create()
						.addressSupplier(server::address)
						.wiretap(true)
						.followRedirect(true)
						.doOnResponse((r, c) -> doOnResponseNanos.add(System.nanoTime()))
						.get()
						.uri("/1")
						.response().map(r -> System.nanoTime())
						.block(Duration.ofSeconds(30));

		assertThat(responseNanos)
				.isGreaterThan(doOnResponseNanos.poll(5, TimeUnit.SECONDS))
				.isGreaterThan(doOnResponseNanos.poll(5, TimeUnit.SECONDS));

		server.disposeNow();
	}

	@Test
	public void testIssue253() {
		final int serverPort1 = SocketUtils.findAvailableTcpPort();

		DisposableServer server =
				HttpServer.create()
				          .port(serverPort1)
				          .host("localhost")
				          .wiretap(true)
				          .route(r -> r.get("/1",
				                                   (req, res) -> res.sendRedirect("http://localhost:" + serverPort1 + "/3"))
				                       .get("/2",
				                                   (req, res) -> res.status(301)
				                                                    .header(HttpHeaderNames.LOCATION, "http://localhost:" + serverPort1 + "/3")
{'fraction_non_alphanumeric': 0.12409205077727242, 'fraction_numerical': 0.010046839997284639, 'mean_word_length': 2.3558086560364466, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 46, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 16, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '936044', 'n_tokens_mistral': 4862, 'n_tokens_neox': 4011, 'n_words': 799}