Path: blob/master/test/jdk/java/net/httpclient/ForbiddenHeadTest.java
66644 views
/*1* Copyright (c) 2020, 2021, 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.ITestResult;52import org.testng.SkipException;53import org.testng.annotations.AfterClass;54import org.testng.annotations.AfterTest;55import org.testng.annotations.BeforeMethod;56import org.testng.annotations.BeforeTest;57import org.testng.annotations.DataProvider;58import org.testng.annotations.Test;5960import javax.net.ssl.SSLContext;61import java.io.IOException;62import java.io.InputStream;63import java.net.Authenticator;64import java.net.InetAddress;65import java.net.InetSocketAddress;66import java.net.PasswordAuthentication;67import java.net.Proxy;68import java.net.ProxySelector;69import java.net.SocketAddress;70import java.net.URI;71import java.net.http.HttpClient;72import java.net.http.HttpRequest;73import java.net.http.HttpResponse;74import java.net.http.HttpResponse.BodyHandlers;75import java.util.ArrayList;76import java.util.Arrays;77import java.util.List;78import java.util.Optional;79import java.util.concurrent.ConcurrentHashMap;80import java.util.concurrent.ConcurrentMap;81import java.util.concurrent.ExecutionException;82import java.util.concurrent.Executor;83import java.util.concurrent.Executors;84import java.util.concurrent.atomic.AtomicLong;85import java.util.concurrent.atomic.AtomicReference;8687import static java.lang.System.err;88import static java.lang.System.out;89import static java.nio.charset.StandardCharsets.UTF_8;90import static org.testng.Assert.assertEquals;91import static org.testng.Assert.assertNotNull;9293public class ForbiddenHeadTest implements HttpServerAdapters {9495SSLContext sslContext;96HttpTestServer httpTestServer; // HTTP/1.197HttpTestServer httpsTestServer; // HTTPS/1.198HttpTestServer http2TestServer; // HTTP/2 ( h2c )99HttpTestServer https2TestServer; // HTTP/2 ( h2 )100DigestEchoServer.TunnelingProxy proxy;101DigestEchoServer.TunnelingProxy authproxy;102String httpURI;103String httpsURI;104String http2URI;105String https2URI;106HttpClient authClient;107HttpClient noAuthClient;108109final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;110static final long SLEEP_AFTER_TEST = 0; // milliseconds111static final int ITERATIONS = 3;112static final Executor executor = new TestExecutor(Executors.newCachedThreadPool());113static final ConcurrentMap<String, Throwable> FAILURES = new ConcurrentHashMap<>();114static volatile boolean tasksFailed;115static final AtomicLong serverCount = new AtomicLong();116static final AtomicLong clientCount = new AtomicLong();117static final long start = System.nanoTime();118public static String now() {119long now = System.nanoTime() - start;120long secs = now / 1000_000_000;121long mill = (now % 1000_000_000) / 1000_000;122long nan = now % 1000_000;123return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);124}125126static class TestExecutor implements Executor {127final AtomicLong tasks = new AtomicLong();128Executor executor;129TestExecutor(Executor executor) {130this.executor = executor;131}132133@Override134public void execute(Runnable command) {135long id = tasks.incrementAndGet();136executor.execute(() -> {137try {138command.run();139} catch (Throwable t) {140tasksFailed = true;141out.printf(now() + "Task %s failed: %s%n", id, t);142err.printf(now() + "Task %s failed: %s%n", id, t);143FAILURES.putIfAbsent("Task " + id, t);144throw t;145}146});147}148}149150protected boolean stopAfterFirstFailure() {151return Boolean.getBoolean("jdk.internal.httpclient.debug");152}153154final AtomicReference<SkipException> skiptests = new AtomicReference<>();155void checkSkip() {156var skip = skiptests.get();157if (skip != null) throw skip;158}159static String name(ITestResult result) {160var params = result.getParameters();161return result.getName()162+ (params == null ? "()" : Arrays.toString(result.getParameters()));163}164165@BeforeMethod166void beforeMethod(ITestContext context) {167if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {168if (skiptests.get() == null) {169SkipException skip = new SkipException("some tests failed");170skip.setStackTrace(new StackTraceElement[0]);171skiptests.compareAndSet(null, skip);172}173}174}175176@AfterClass177static final void printFailedTests(ITestContext context) {178out.println("\n=========================");179try {180// Exceptions should already have been added to FAILURES181// var failed = context.getFailedTests().getAllResults().stream()182// .collect(Collectors.toMap(r -> name(r), ITestResult::getThrowable));183// FAILURES.putAll(failed);184185out.printf("%n%sCreated %d servers and %d clients%n",186now(), serverCount.get(), clientCount.get());187if (FAILURES.isEmpty()) return;188out.println("Failed tests: ");189FAILURES.entrySet().forEach((e) -> {190out.printf("\t%s: %s%n", e.getKey(), e.getValue());191e.getValue().printStackTrace(out);192e.getValue().printStackTrace();193});194if (tasksFailed) {195out.println("WARNING: Some tasks failed");196}197} finally {198out.println("\n=========================\n");199}200}201202static final int UNAUTHORIZED = 401;203static final int PROXY_UNAUTHORIZED = 407;204static final int FORBIDDEN = 403;205static final int HTTP_OK = 200;206static final String MESSAGE = "Unauthorized";207208209@DataProvider(name = "all")210public Object[][] allcases() {211List<Object[]> result = new ArrayList<>();212for (var client : List.of(authClient, noAuthClient)) {213for (boolean async : List.of(true, false)) {214for (int code : List.of(UNAUTHORIZED, PROXY_UNAUTHORIZED)) {215var srv = code == PROXY_UNAUTHORIZED ? "/proxy" : "/server";216for (var auth : List.of("/auth", "/noauth")) {217var pcode = code;218if (auth.equals("/noauth")) {219if (client == authClient) continue;220pcode = FORBIDDEN;221}222for (var uri : List.of(httpURI, httpsURI, http2URI, https2URI)) {223result.add(new Object[]{uri + srv + auth, pcode, async, client});224}225}226}227}228}229return result.toArray(new Object[0][0]);230}231232static final AtomicLong requestCounter = new AtomicLong();233234static final Authenticator authenticator = new Authenticator() {235@Override236protected PasswordAuthentication getPasswordAuthentication() {237return new PasswordAuthentication("arthur",new char[] {'d', 'e', 'n', 't'});238}239};240241static final AtomicLong sleepCount = new AtomicLong();242243@Test(dataProvider = "all")244void test(String uriString, int code, boolean async, HttpClient client) throws Throwable {245checkSkip();246var name = String.format("test(%s, %d, %s, %s)", uriString, code, async ? "async" : "sync",247client.authenticator().isPresent() ? "authClient" : "noAuthClient");248out.printf("%n---- starting %s ----%n", name);249assert client.authenticator().isPresent() ? client == authClient : client == noAuthClient;250uriString = uriString + "/ForbiddenTest";251for (int i=0; i<ITERATIONS; i++) {252if (ITERATIONS > 1) out.printf("---- ITERATION %d%n",i);253try {254doTest(uriString, code, async, client);255long count = sleepCount.incrementAndGet();256System.err.println(now() + " Sleeping: " + count);257Thread.sleep(SLEEP_AFTER_TEST);258System.err.println(now() + " Waking up: " + count);259} catch (Throwable x) {260FAILURES.putIfAbsent(name, x);261throw x;262}263}264}265266static String authHeaderName(int code) {267return switch (code) {268case UNAUTHORIZED -> "WWW-Authenticate";269case PROXY_UNAUTHORIZED -> "Proxy-Authenticate";270default -> null;271};272}273274private void doTest(String uriString, int code, boolean async, HttpClient client) throws Throwable {275URI uri = URI.create(uriString);276277HttpRequest.Builder requestBuilder = HttpRequest278.newBuilder(uri)279.method("HEAD", HttpRequest.BodyPublishers.noBody());280281HttpRequest request = requestBuilder.build();282out.println("Initial request: " + request.uri());283284String header = authHeaderName(code);285// the request is expected to return 403 Forbidden if the client is authenticated,286// or the server doesn't require authentication, 401 or 407 otherwise.287boolean forbidden = client.authenticator().isPresent() || code == FORBIDDEN;288289HttpResponse<String> response = null;290if (async) {291response = client.send(request, BodyHandlers.ofString());292} else {293try {294response = client.sendAsync(request, BodyHandlers.ofString()).get();295} catch (ExecutionException ex) {296throw ex.getCause();297}298}299300String prefix = uriString.contains("/proxy/") ? "Proxy-" : "WWW-";301String expectedValue;302if (forbidden) {303// The message body is generated by the server, after authentication was304// successful.305expectedValue = prefix + "FORBIDDEN";306} else if (uriString.contains("/proxy/") && uri.getScheme().equalsIgnoreCase("https")) {307// In that case the tunnelling proxy itself is expected to return 407,308// and the message will have no body (since the CONNECT request fails).309assert code == PROXY_UNAUTHORIZED;310expectedValue = null;311} else {312// the message body is generated by our fake server pretending to be313// a proxy.314expectedValue = prefix + MESSAGE;315}316317318out.println(" Got response: " + response);319assertEquals(response.statusCode(), forbidden? FORBIDDEN : code);320assertEquals(response.body(), expectedValue == null ? null : "");321assertEquals(response.headers().firstValue("X-value"), Optional.ofNullable(expectedValue));322// when the CONNECT request fails, its body is discarded - but323// the response header may still contain its content length.324// don't check content length in that case.325if (expectedValue != null) {326String clen = String.valueOf(expectedValue.getBytes(UTF_8).length);327assertEquals(response.headers().firstValue("Content-Length"), Optional.of(clen));328}329330}331332// -- Infrastructure333334@BeforeTest335public void setup() throws Exception {336sslContext = new SimpleSSLContext().get();337if (sslContext == null)338throw new AssertionError("Unexpected null sslContext");339340InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);341342httpTestServer = HttpTestServer.of(HttpServer.create(sa, 0));343httpTestServer.addHandler(new UnauthorizedHandler(), "/http1/");344httpTestServer.addHandler(new UnauthorizedHandler(), "/http2/proxy/");345httpURI = "http://" + httpTestServer.serverAuthority() + "/http1";346HttpsServer httpsServer = HttpsServer.create(sa, 0);347httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));348httpsTestServer = HttpTestServer.of(httpsServer);349httpsTestServer.addHandler(new UnauthorizedHandler(),"/https1/");350httpsURI = "https://" + httpsTestServer.serverAuthority() + "/https1";351352http2TestServer = HttpTestServer.of(new Http2TestServer("localhost", false, 0));353http2TestServer.addHandler(new UnauthorizedHandler(), "/http2/");354http2URI = "http://" + http2TestServer.serverAuthority() + "/http2";355https2TestServer = HttpTestServer.of(new Http2TestServer("localhost", true, sslContext));356https2TestServer.addHandler(new UnauthorizedHandler(), "/https2/");357https2URI = "https://" + https2TestServer.serverAuthority() + "/https2";358359proxy = DigestEchoServer.createHttpsProxyTunnel(DigestEchoServer.HttpAuthSchemeType.NONE);360authproxy = DigestEchoServer.createHttpsProxyTunnel(DigestEchoServer.HttpAuthSchemeType.BASIC);361362authClient = TRACKER.track(HttpClient.newBuilder()363.proxy(TestProxySelector.of(proxy, authproxy, httpTestServer))364.sslContext(sslContext)365.executor(executor)366.authenticator(authenticator)367.build());368clientCount.incrementAndGet();369370noAuthClient = TRACKER.track(HttpClient.newBuilder()371.proxy(TestProxySelector.of(proxy, authproxy, httpTestServer))372.sslContext(sslContext)373.executor(executor)374.build());375clientCount.incrementAndGet();376377httpTestServer.start();378serverCount.incrementAndGet();379httpsTestServer.start();380serverCount.incrementAndGet();381http2TestServer.start();382serverCount.incrementAndGet();383https2TestServer.start();384serverCount.incrementAndGet();385}386387@AfterTest388public void teardown() throws Exception {389authClient = noAuthClient = null;390Thread.sleep(100);391AssertionError fail = TRACKER.check(500);392393proxy.stop();394authproxy.stop();395httpTestServer.stop();396httpsTestServer.stop();397http2TestServer.stop();398https2TestServer.stop();399}400401static class TestProxySelector extends ProxySelector {402final DigestEchoServer.TunnelingProxy proxy;403final DigestEchoServer.TunnelingProxy authproxy;404final HttpTestServer plain;405private TestProxySelector(DigestEchoServer.TunnelingProxy proxy,406DigestEchoServer.TunnelingProxy authproxy,407HttpTestServer plain) {408this.proxy = proxy;409this.authproxy = authproxy;410this.plain = plain;411}412@Override413public List<Proxy> select(URI uri) {414String path = uri.getPath();415out.println("Selecting proxy for: " + uri);416if (path.contains("/proxy/")) {417if (path.contains("/http1/")) {418// Simple proxying - in our test the server pretends419// to be the proxy.420System.out.print("PROXY is server for " + uri);421return List.of(new Proxy(Proxy.Type.HTTP,422new InetSocketAddress(uri.getHost(), uri.getPort())));423} else if (path.contains("/http2/")) {424// HTTP/2 is downgraded to HTTP/1.1 if there is a proxy425System.out.print("PROXY is plain server for " + uri);426return List.of(new Proxy(Proxy.Type.HTTP, plain.getAddress()));427} else {428// Both HTTPS or HTTPS/2 require tunnelling429var p = path.contains("/auth/") ? authproxy : proxy;430if (p == authproxy) {431out.println("PROXY is authenticating tunneling proxy for " + uri);432} else {433out.println("PROXY is plain tunneling proxy for " + uri);434}435return List.of(new Proxy(Proxy.Type.HTTP, p.getProxyAddress()));436}437}438System.out.print("NO_PROXY for " + uri);439return List.of(Proxy.NO_PROXY);440}441@Override442public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {443System.err.printf("Connect failed for: uri=\"%s\", sa=\"%s\", ioe=%s%n", uri, sa, ioe);444}445public static TestProxySelector of(DigestEchoServer.TunnelingProxy proxy,446DigestEchoServer.TunnelingProxy authproxy,447HttpTestServer plain) {448return new TestProxySelector(proxy, authproxy, plain);449}450}451452static class UnauthorizedHandler implements HttpTestHandler {453454@Override455public void handle(HttpTestExchange t) throws IOException {456readAllRequestData(t); // shouldn't be any457String method = t.getRequestMethod();458String path = t.getRequestURI().getPath();459HttpTestRequestHeaders reqh = t.getRequestHeaders();460HttpTestResponseHeaders rsph = t.getResponseHeaders();461462String xValue;463boolean noAuthRequired = path.contains("/noauth/");464boolean authenticated = path.contains("/server/") && reqh.containsKey("Authorization")465|| path.contains("/proxy/") && reqh.containsKey("Proxy-Authorization")466|| path.contains("/proxy/") && (path.contains("/https1/") || path.contains("/https2/"));467String srv = path.contains("/proxy/") ? "proxy" : "server";468String prefix = path.contains("/proxy/") ? "Proxy-" : "WWW-";469int authcode = path.contains("/proxy/") ? PROXY_UNAUTHORIZED : UNAUTHORIZED;470int code = (authenticated || noAuthRequired) ? FORBIDDEN : authcode;471if (authenticated || noAuthRequired) {472xValue = prefix + "FORBIDDEN";473} else {474xValue = prefix + MESSAGE;475rsph.addHeader(prefix + "Authenticate", "Basic realm=\"earth\", charset=\"UTF-8\"");476}477478t.getResponseHeaders().addHeader("X-value", xValue);479t.getResponseHeaders().addHeader("Content-Length", String.valueOf(xValue.getBytes(UTF_8).length));480t.sendResponseHeaders(code, 0);481}482}483484static void readAllRequestData(HttpTestExchange t) throws IOException {485try (InputStream is = t.getRequestBody()) {486is.readAllBytes();487}488}489}490491492