Path: blob/master/test/jdk/java/net/httpclient/ForbiddenHeadTest.java
41149 views
/*1* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @summary checks that receiving 403 for a HEAD request after26* 401/407 doesn't cause any unexpected behavior.27* @modules java.base/sun.net.www.http28* java.net.http/jdk.internal.net.http.common29* java.net.http/jdk.internal.net.http.frame30* java.net.http/jdk.internal.net.http.hpack31* java.logging32* jdk.httpserver33* java.base/sun.net.www.http34* java.base/sun.net.www35* java.base/sun.net36* @library /test/lib http2/server37* @build HttpServerAdapters DigestEchoServer Http2TestServer ForbiddenHeadTest38* @build jdk.test.lib.net.SimpleSSLContext39* @run testng/othervm40* -Djdk.http.auth.tunneling.disabledSchemes41* -Djdk.httpclient.HttpClient.log=headers,requests42* -Djdk.internal.httpclient.debug=true43* ForbiddenHeadTest44*/4546import com.sun.net.httpserver.HttpServer;47import com.sun.net.httpserver.HttpsConfigurator;48import com.sun.net.httpserver.HttpsServer;49import jdk.test.lib.net.SimpleSSLContext;50import org.testng.ITestContext;51import org.testng.annotations.AfterClass;52import org.testng.annotations.AfterTest;53import org.testng.annotations.BeforeMethod;54import org.testng.annotations.BeforeTest;55import org.testng.annotations.DataProvider;56import org.testng.annotations.Test;5758import javax.net.ssl.SSLContext;59import java.io.IOException;60import java.io.InputStream;61import java.net.Authenticator;62import java.net.InetAddress;63import java.net.InetSocketAddress;64import java.net.PasswordAuthentication;65import java.net.Proxy;66import java.net.ProxySelector;67import java.net.SocketAddress;68import java.net.URI;69import java.net.http.HttpClient;70import java.net.http.HttpRequest;71import java.net.http.HttpResponse;72import java.net.http.HttpResponse.BodyHandlers;73import java.util.ArrayList;74import java.util.List;75import java.util.Optional;76import java.util.concurrent.ConcurrentHashMap;77import java.util.concurrent.ConcurrentMap;78import java.util.concurrent.ExecutionException;79import java.util.concurrent.Executor;80import java.util.concurrent.Executors;81import java.util.concurrent.atomic.AtomicLong;8283import static java.lang.System.err;84import static java.lang.System.out;85import static java.nio.charset.StandardCharsets.UTF_8;86import static org.testng.Assert.assertEquals;87import static org.testng.Assert.assertNotNull;8889public class ForbiddenHeadTest implements HttpServerAdapters {9091SSLContext sslContext;92HttpTestServer httpTestServer; // HTTP/1.193HttpTestServer httpsTestServer; // HTTPS/1.194HttpTestServer http2TestServer; // HTTP/2 ( h2c )95HttpTestServer https2TestServer; // HTTP/2 ( h2 )96DigestEchoServer.TunnelingProxy proxy;97DigestEchoServer.TunnelingProxy authproxy;98String httpURI;99String httpsURI;100String http2URI;101String https2URI;102HttpClient authClient;103HttpClient noAuthClient;104105final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;106static final long SLEEP_AFTER_TEST = 0; // milliseconds107static final int ITERATIONS = 3;108static final Executor executor = new TestExecutor(Executors.newCachedThreadPool());109static final ConcurrentMap<String, Throwable> FAILURES = new ConcurrentHashMap<>();110static volatile boolean tasksFailed;111static final AtomicLong serverCount = new AtomicLong();112static final AtomicLong clientCount = new AtomicLong();113static final long start = System.nanoTime();114public static String now() {115long now = System.nanoTime() - start;116long secs = now / 1000_000_000;117long mill = (now % 1000_000_000) / 1000_000;118long nan = now % 1000_000;119return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);120}121122static class TestExecutor implements Executor {123final AtomicLong tasks = new AtomicLong();124Executor executor;125TestExecutor(Executor executor) {126this.executor = executor;127}128129@Override130public void execute(Runnable command) {131long id = tasks.incrementAndGet();132executor.execute(() -> {133try {134command.run();135} catch (Throwable t) {136tasksFailed = true;137out.printf(now() + "Task %s failed: %s%n", id, t);138err.printf(now() + "Task %s failed: %s%n", id, t);139FAILURES.putIfAbsent("Task " + id, t);140throw t;141}142});143}144}145146protected boolean stopAfterFirstFailure() {147return Boolean.getBoolean("jdk.internal.httpclient.debug");148}149150@BeforeMethod151void beforeMethod(ITestContext context) {152if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {153throw new RuntimeException("some tests failed");154}155}156157@AfterClass158static final void printFailedTests() {159out.println("\n=========================");160try {161out.printf("%n%sCreated %d servers and %d clients%n",162now(), serverCount.get(), clientCount.get());163if (FAILURES.isEmpty()) return;164out.println("Failed tests: ");165FAILURES.entrySet().forEach((e) -> {166out.printf("\t%s: %s%n", e.getKey(), e.getValue());167e.getValue().printStackTrace(out);168e.getValue().printStackTrace();169});170if (tasksFailed) {171out.println("WARNING: Some tasks failed");172}173} finally {174out.println("\n=========================\n");175}176}177178static final int UNAUTHORIZED = 401;179static final int PROXY_UNAUTHORIZED = 407;180static final int FORBIDDEN = 403;181static final int HTTP_OK = 200;182static final String MESSAGE = "Unauthorized";183184185@DataProvider(name = "all")186public Object[][] allcases() {187List<Object[]> result = new ArrayList<>();188for (var client : List.of(authClient, noAuthClient)) {189for (boolean async : List.of(true, false)) {190for (int code : List.of(UNAUTHORIZED, PROXY_UNAUTHORIZED)) {191var srv = code == PROXY_UNAUTHORIZED ? "/proxy" : "/server";192for (var auth : List.of("/auth", "/noauth")) {193var pcode = code;194if (auth.equals("/noauth")) {195if (client == authClient) continue;196pcode = FORBIDDEN;197}198for (var uri : List.of(httpURI, httpsURI, http2URI, https2URI)) {199result.add(new Object[]{uri + srv + auth, pcode, async, client});200}201}202}203}204}205return result.toArray(new Object[0][0]);206}207208static final AtomicLong requestCounter = new AtomicLong();209210static final Authenticator authenticator = new Authenticator() {211@Override212protected PasswordAuthentication getPasswordAuthentication() {213return new PasswordAuthentication("arthur",new char[] {'d', 'e', 'n', 't'});214}215};216217static final AtomicLong sleepCount = new AtomicLong();218219@Test(dataProvider = "all")220void test(String uriString, int code, boolean async, HttpClient client) throws Throwable {221var name = String.format("test(%s, %d, %s, %s)", uriString, code, async ? "async" : "sync",222client.authenticator().isPresent() ? "authClient" : "noAuthClient");223out.printf("%n---- starting %s ----%n", name);224assert client.authenticator().isPresent() ? client == authClient : client == noAuthClient;225uriString = uriString + "/ForbiddenTest";226for (int i=0; i<ITERATIONS; i++) {227if (ITERATIONS > 1) out.printf("---- ITERATION %d%n",i);228try {229doTest(uriString, code, async, client);230long count = sleepCount.incrementAndGet();231System.err.println(now() + " Sleeping: " + count);232Thread.sleep(SLEEP_AFTER_TEST);233System.err.println(now() + " Waking up: " + count);234} catch (Throwable x) {235FAILURES.putIfAbsent(name, x);236throw x;237}238}239}240241static String authHeaderName(int code) {242return switch (code) {243case UNAUTHORIZED -> "WWW-Authenticate";244case PROXY_UNAUTHORIZED -> "Proxy-Authenticate";245default -> null;246};247}248249private void doTest(String uriString, int code, boolean async, HttpClient client) throws Throwable {250URI uri = URI.create(uriString);251252HttpRequest.Builder requestBuilder = HttpRequest253.newBuilder(uri)254.method("HEAD", HttpRequest.BodyPublishers.noBody());255256HttpRequest request = requestBuilder.build();257out.println("Initial request: " + request.uri());258259String header = authHeaderName(code);260// the request is expected to return 403 Forbidden if the client is authenticated,261// or the server doesn't require authentication, 401 or 407 otherwise.262boolean forbidden = client.authenticator().isPresent() || code == FORBIDDEN;263264HttpResponse<String> response = null;265if (async) {266response = client.send(request, BodyHandlers.ofString());267} else {268try {269response = client.sendAsync(request, BodyHandlers.ofString()).get();270} catch (ExecutionException ex) {271throw ex.getCause();272}273}274275String prefix = uriString.contains("/proxy/") ? "Proxy-" : "WWW-";276String expectedValue;277if (forbidden) {278// The message body is generated by the server, after authentication was279// successful.280expectedValue = prefix + "FORBIDDEN";281} else if (uriString.contains("/proxy/") && uri.getScheme().equalsIgnoreCase("https")) {282// In that case the tunnelling proxy itself is expected to return 407,283// and the message will have no body (since the CONNECT request fails).284assert code == PROXY_UNAUTHORIZED;285expectedValue = null;286} else {287// the message body is generated by our fake server pretending to be288// a proxy.289expectedValue = prefix + MESSAGE;290}291292293out.println(" Got response: " + response);294assertEquals(response.statusCode(), forbidden? FORBIDDEN : code);295assertEquals(response.body(), expectedValue == null ? null : "");296assertEquals(response.headers().firstValue("X-value"), Optional.ofNullable(expectedValue));297// when the CONNECT request fails, its body is discarded - but298// the response header may still contain its content length.299// don't check content length in that case.300if (expectedValue != null) {301String clen = String.valueOf(expectedValue.getBytes(UTF_8).length);302assertEquals(response.headers().firstValue("Content-Length"), Optional.of(clen));303}304305}306307// -- Infrastructure308309@BeforeTest310public void setup() throws Exception {311sslContext = new SimpleSSLContext().get();312if (sslContext == null)313throw new AssertionError("Unexpected null sslContext");314315InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);316317httpTestServer = HttpTestServer.of(HttpServer.create(sa, 0));318httpTestServer.addHandler(new UnauthorizedHandler(), "/http1/");319httpTestServer.addHandler(new UnauthorizedHandler(), "/http2/proxy/");320httpURI = "http://" + httpTestServer.serverAuthority() + "/http1";321HttpsServer httpsServer = HttpsServer.create(sa, 0);322httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));323httpsTestServer = HttpTestServer.of(httpsServer);324httpsTestServer.addHandler(new UnauthorizedHandler(),"/https1/");325httpsURI = "https://" + httpsTestServer.serverAuthority() + "/https1";326327http2TestServer = HttpTestServer.of(new Http2TestServer("localhost", false, 0));328http2TestServer.addHandler(new UnauthorizedHandler(), "/http2/");329http2URI = "http://" + http2TestServer.serverAuthority() + "/http2";330https2TestServer = HttpTestServer.of(new Http2TestServer("localhost", true, sslContext));331https2TestServer.addHandler(new UnauthorizedHandler(), "/https2/");332https2URI = "https://" + https2TestServer.serverAuthority() + "/https2";333334proxy = DigestEchoServer.createHttpsProxyTunnel(DigestEchoServer.HttpAuthSchemeType.NONE);335authproxy = DigestEchoServer.createHttpsProxyTunnel(DigestEchoServer.HttpAuthSchemeType.BASIC);336337authClient = TRACKER.track(HttpClient.newBuilder()338.proxy(TestProxySelector.of(proxy, authproxy, httpTestServer))339.sslContext(sslContext)340.executor(executor)341.authenticator(authenticator)342.build());343clientCount.incrementAndGet();344345noAuthClient = TRACKER.track(HttpClient.newBuilder()346.proxy(TestProxySelector.of(proxy, authproxy, httpTestServer))347.sslContext(sslContext)348.executor(executor)349.build());350clientCount.incrementAndGet();351352httpTestServer.start();353serverCount.incrementAndGet();354httpsTestServer.start();355serverCount.incrementAndGet();356http2TestServer.start();357serverCount.incrementAndGet();358https2TestServer.start();359serverCount.incrementAndGet();360}361362@AfterTest363public void teardown() throws Exception {364authClient = noAuthClient = null;365Thread.sleep(100);366AssertionError fail = TRACKER.check(500);367368proxy.stop();369authproxy.stop();370httpTestServer.stop();371httpsTestServer.stop();372http2TestServer.stop();373https2TestServer.stop();374}375376static class TestProxySelector extends ProxySelector {377final DigestEchoServer.TunnelingProxy proxy;378final DigestEchoServer.TunnelingProxy authproxy;379final HttpTestServer plain;380private TestProxySelector(DigestEchoServer.TunnelingProxy proxy,381DigestEchoServer.TunnelingProxy authproxy,382HttpTestServer plain) {383this.proxy = proxy;384this.authproxy = authproxy;385this.plain = plain;386}387@Override388public List<Proxy> select(URI uri) {389String path = uri.getPath();390out.println("Selecting proxy for: " + uri);391if (path.contains("/proxy/")) {392if (path.contains("/http1/")) {393// Simple proxying - in our test the server pretends394// to be the proxy.395System.out.print("PROXY is server for " + uri);396return List.of(new Proxy(Proxy.Type.HTTP,397new InetSocketAddress(uri.getHost(), uri.getPort())));398} else if (path.contains("/http2/")) {399// HTTP/2 is downgraded to HTTP/1.1 if there is a proxy400System.out.print("PROXY is plain server for " + uri);401return List.of(new Proxy(Proxy.Type.HTTP, plain.getAddress()));402} else {403// Both HTTPS or HTTPS/2 require tunnelling404var p = path.contains("/auth/") ? authproxy : proxy;405if (p == authproxy) {406out.println("PROXY is authenticating tunneling proxy for " + uri);407} else {408out.println("PROXY is plain tunneling proxy for " + uri);409}410return List.of(new Proxy(Proxy.Type.HTTP, p.getProxyAddress()));411}412}413System.out.print("NO_PROXY for " + uri);414return List.of(Proxy.NO_PROXY);415}416@Override417public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {418System.err.printf("Connect failed for: uri=\"%s\", sa=\"%s\", ioe=%s%n", uri, sa, ioe);419}420public static TestProxySelector of(DigestEchoServer.TunnelingProxy proxy,421DigestEchoServer.TunnelingProxy authproxy,422HttpTestServer plain) {423return new TestProxySelector(proxy, authproxy, plain);424}425}426427static class UnauthorizedHandler implements HttpTestHandler {428429@Override430public void handle(HttpTestExchange t) throws IOException {431readAllRequestData(t); // shouldn't be any432String method = t.getRequestMethod();433String path = t.getRequestURI().getPath();434HttpTestRequestHeaders reqh = t.getRequestHeaders();435HttpTestResponseHeaders rsph = t.getResponseHeaders();436437String xValue;438boolean noAuthRequired = path.contains("/noauth/");439boolean authenticated = path.contains("/server/") && reqh.containsKey("Authorization")440|| path.contains("/proxy/") && reqh.containsKey("Proxy-Authorization")441|| path.contains("/proxy/") && (path.contains("/https1/") || path.contains("/https2/"));442String srv = path.contains("/proxy/") ? "proxy" : "server";443String prefix = path.contains("/proxy/") ? "Proxy-" : "WWW-";444int authcode = path.contains("/proxy/") ? PROXY_UNAUTHORIZED : UNAUTHORIZED;445int code = (authenticated || noAuthRequired) ? FORBIDDEN : authcode;446if (authenticated || noAuthRequired) {447xValue = prefix + "FORBIDDEN";448} else {449xValue = prefix + MESSAGE;450rsph.addHeader(prefix + "Authenticate", "Basic realm=\"earth\", charset=\"UTF-8\"");451}452453t.getResponseHeaders().addHeader("X-value", xValue);454t.getResponseHeaders().addHeader("Content-Length", String.valueOf(xValue.getBytes(UTF_8).length));455t.sendResponseHeaders(code, 0);456}457}458459static void readAllRequestData(HttpTestExchange t) throws IOException {460try (InputStream is = t.getRequestBody()) {461is.readAllBytes();462}463}464}465466467