File: HttpRedirectTest.java

package info (click to toggle)
openjdk-21 21.0.8%2B9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 823,976 kB
  • sloc: java: 5,613,338; xml: 1,643,607; cpp: 1,296,296; ansic: 420,291; asm: 404,850; objc: 20,994; sh: 15,271; javascript: 11,245; python: 6,895; makefile: 2,362; perl: 357; awk: 351; sed: 172; jsp: 24; csh: 3
file content (450 lines) | stat: -rw-r--r-- 19,185 bytes parent folder | download | duplicates (10)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
/*
 * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
import com.sun.net.httpserver.HttpsServer;
import jdk.httpclient.test.lib.common.TestServerConfigurator;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpClient.Version.HTTP_2;
import static org.testng.Assert.*;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import jdk.httpclient.test.lib.common.HttpServerAdapters;

/**
 * @test
 * @bug 8232625
 * @summary This test verifies that the HttpClient works correctly when redirecting a post request.
 * @library /test/lib /test/jdk/java/net/httpclient/lib
 * @build jdk.test.lib.net.SimpleSSLContext DigestEchoServer HttpRedirectTest
 *        jdk.httpclient.test.lib.common.HttpServerAdapters
 *        jdk.httpclient.test.lib.common.TestServerConfigurator
 * @run testng/othervm -Dtest.requiresHost=true
 *                   -Djdk.httpclient.HttpClient.log=headers
 *                   -Djdk.internal.httpclient.debug=false
 *                   HttpRedirectTest
 *
 */
public class HttpRedirectTest implements HttpServerAdapters {
    static final String GET_RESPONSE_BODY = "Lorem ipsum dolor sit amet";
    static final String REQUEST_BODY = "Here it goes";
    static final SSLContext context;
    static {
        try {
            context = new SimpleSSLContext().get();
            SSLContext.setDefault(context);
        } catch (Exception x) {
            throw new ExceptionInInitializerError(x);
        }
    }

    final AtomicLong requestCounter = new AtomicLong();
    final AtomicLong responseCounter = new AtomicLong();
    HttpTestServer http1Server;
    HttpTestServer http2Server;
    HttpTestServer https1Server;
    HttpTestServer https2Server;
    DigestEchoServer.TunnelingProxy proxy;

    URI http1URI;
    URI https1URI;
    URI http2URI;
    URI https2URI;
    InetSocketAddress proxyAddress;
    ProxySelector proxySelector;
    HttpClient client;
    List<CompletableFuture<?>>  futures = new CopyOnWriteArrayList<>();
    Set<URI> pending = new CopyOnWriteArraySet<>();

    final ExecutorService executor = new ThreadPoolExecutor(12, 60, 10,
            TimeUnit.SECONDS, new LinkedBlockingQueue<>()); // Shared by HTTP/1.1 servers
    final ExecutorService clientexec = new ThreadPoolExecutor(6, 12, 1,
            TimeUnit.SECONDS, new LinkedBlockingQueue<>()); // Used by the client

    public HttpClient newHttpClient(ProxySelector ps) {
        HttpClient.Builder builder = HttpClient
                .newBuilder()
                .sslContext(context)
                .executor(clientexec)
                .followRedirects(HttpClient.Redirect.ALWAYS)
                .proxy(ps);
        return builder.build();
    }

    @DataProvider(name="uris")
    Object[][] testURIs() throws URISyntaxException {
        List<URI> uris = List.of(
                http1URI.resolve("direct/orig/"),
                https1URI.resolve("direct/orig/"),
                https1URI.resolve("proxy/orig/"),
                http2URI.resolve("direct/orig/"),
                https2URI.resolve("direct/orig/"),
                https2URI.resolve("proxy/orig/"));
        List<Map.Entry<Integer, String>> redirects = List.of(
                Map.entry(301, "GET"),
                Map.entry(308, "POST"),
                Map.entry(302, "GET"),
                Map.entry(303, "GET"),
                Map.entry(307, "POST"),
                Map.entry(300, "DO_NOT_FOLLOW"),
                Map.entry(304, "DO_NOT_FOLLOW"),
                Map.entry(305, "DO_NOT_FOLLOW"),
                Map.entry(306, "DO_NOT_FOLLOW"),
                Map.entry(309, "DO_NOT_FOLLOW"),
                Map.entry(new Random().nextInt(90) + 310, "DO_NOT_FOLLOW")
        );
        Object[][] tests = new Object[redirects.size() * uris.size()][3];
        int count = 0;
        for (int i=0; i < uris.size(); i++) {
            URI u = uris.get(i);
            for (int j=0; j < redirects.size() ; j++) {
                int code = redirects.get(j).getKey();
                String m = redirects.get(j).getValue();
                tests[count][0] = u.resolve(code +"/");
                tests[count][1] = code;
                tests[count][2] = m;
                count++;
            }
        }
        return tests;
    }

    @BeforeClass
    public void setUp() throws Exception {
        try {
            InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);

            // HTTP/1.1
            http1Server = HttpTestServer.create(HTTP_1_1, null, executor);
            http1Server.addHandler(new HttpTestRedirectHandler("http", http1Server),
                    "/HttpRedirectTest/http1/");
            http1Server.start();
            http1URI = new URI("http://" + http1Server.serverAuthority() + "/HttpRedirectTest/http1/");


            // HTTPS/1.1
            HttpsServer sserver1 = HttpsServer.create(sa, 100);
            sserver1.setExecutor(executor);
            sserver1.setHttpsConfigurator(new TestServerConfigurator(sa.getAddress(), context));
            https1Server = HttpTestServer.of(sserver1);
            https1Server.addHandler(new HttpTestRedirectHandler("https", https1Server),
                    "/HttpRedirectTest/https1/");
            https1Server.start();
            https1URI = new URI("https://" + https1Server.serverAuthority() + "/HttpRedirectTest/https1/");

            // HTTP/2.0
            http2Server = HttpTestServer.create(HTTP_2);
            http2Server.addHandler(new HttpTestRedirectHandler("http", http2Server),
                    "/HttpRedirectTest/http2/");
            http2Server.start();
            http2URI = new URI("http://" + http2Server.serverAuthority() + "/HttpRedirectTest/http2/");

            // HTTPS/2.0
            https2Server = HttpTestServer.create(HTTP_2, SSLContext.getDefault());
            https2Server.addHandler(new HttpTestRedirectHandler("https", https2Server),
                    "/HttpRedirectTest/https2/");
            https2Server.start();
            https2URI = new URI("https://" + https2Server.serverAuthority() + "/HttpRedirectTest/https2/");

            proxy = DigestEchoServer.createHttpsProxyTunnel(
                    DigestEchoServer.HttpAuthSchemeType.NONE);
            proxyAddress = proxy.getProxyAddress();
            proxySelector = new HttpProxySelector(proxyAddress);
            client = newHttpClient(proxySelector);
            System.out.println("Setup: done");
        } catch (Exception x) {
            tearDown(); throw x;
        } catch (Error e) {
            tearDown(); throw e;
        }
    }

    private void testNonIdempotent(URI u, HttpRequest request,
                                   int code, String method) throws Exception {
        System.out.println("Testing with " + u);
        CompletableFuture<HttpResponse<String>> respCf =
                client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
        HttpResponse<String> resp = respCf.join();
        if (method.equals("DO_NOT_FOLLOW")) {
            assertEquals(resp.statusCode(), code, u + ": status code");
        } else {
            assertEquals(resp.statusCode(), 200, u + ": status code");
        }
        if (method.equals("POST")) {
            assertEquals(resp.body(), REQUEST_BODY, u + ": body");
        } else if (code == 304) {
            assertEquals(resp.body(), "", u + ": body");
        } else if (method.equals("DO_NOT_FOLLOW")) {
            assertNotEquals(resp.body(), GET_RESPONSE_BODY, u + ": body");
            assertNotEquals(resp.body(), REQUEST_BODY, u + ": body");
        } else {
            assertEquals(resp.body(), GET_RESPONSE_BODY, u + ": body");
        }
    }

    public void testIdempotent(URI u, HttpRequest request,
                               int code, String method) throws Exception {
        CompletableFuture<HttpResponse<String>> respCf =
                client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
        HttpResponse<String> resp = respCf.join();
        if (method.equals("DO_NOT_FOLLOW")) {
            assertEquals(resp.statusCode(), code, u + ": status code");
        } else {
            assertEquals(resp.statusCode(), 200, u + ": status code");
        }
        if (method.equals("POST")) {
            assertEquals(resp.body(), REQUEST_BODY, u + ": body");
        } else if (code == 304) {
            assertEquals(resp.body(), "", u + ": body");
        } else if (method.equals("DO_NOT_FOLLOW")) {
            assertNotEquals(resp.body(), GET_RESPONSE_BODY, u + ": body");
            assertNotEquals(resp.body(), REQUEST_BODY, u + ": body");
        } else if (code == 303) {
            assertEquals(resp.body(), GET_RESPONSE_BODY, u + ": body");
        } else {
            assertEquals(resp.body(), REQUEST_BODY, u + ": body");
        }
    }

    @Test(dataProvider = "uris")
    public void testPOST(URI uri, int code, String method) throws Exception {
        URI u = uri.resolve("foo?n=" + requestCounter.incrementAndGet());
        HttpRequest request = HttpRequest.newBuilder(u)
                .POST(HttpRequest.BodyPublishers.ofString(REQUEST_BODY)).build();
        // POST is not considered idempotent.
        testNonIdempotent(u, request, code, method);
    }

    @Test(dataProvider = "uris")
    public void testPUT(URI uri, int code, String method) throws Exception {
        URI u = uri.resolve("foo?n=" + requestCounter.incrementAndGet());
        System.out.println("Testing with " + u);
        HttpRequest request = HttpRequest.newBuilder(u)
                .PUT(HttpRequest.BodyPublishers.ofString(REQUEST_BODY)).build();
        // PUT is considered idempotent.
        testIdempotent(u, request, code, method);
    }

    @Test(dataProvider = "uris")
    public void testFoo(URI uri, int code, String method) throws Exception {
        URI u = uri.resolve("foo?n=" + requestCounter.incrementAndGet());
        System.out.println("Testing with " + u);
        HttpRequest request = HttpRequest.newBuilder(u)
                .method("FOO",
                        HttpRequest.BodyPublishers.ofString(REQUEST_BODY)).build();
        // FOO is considered idempotent.
        testIdempotent(u, request, code, method);
    }

    @Test(dataProvider = "uris")
    public void testGet(URI uri, int code, String method) throws Exception {
        URI u = uri.resolve("foo?n=" + requestCounter.incrementAndGet());
        System.out.println("Testing with " + u);
        HttpRequest request = HttpRequest.newBuilder(u)
                .method("GET",
                        HttpRequest.BodyPublishers.ofString(REQUEST_BODY)).build();
        CompletableFuture<HttpResponse<String>> respCf =
                client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
        HttpResponse<String> resp = respCf.join();
        // body will be preserved except for 304 and 303: this is a GET.
        if (method.equals("DO_NOT_FOLLOW")) {
            assertEquals(resp.statusCode(), code, u + ": status code");
        } else {
            assertEquals(resp.statusCode(), 200, u + ": status code");
        }
        if (code == 304) {
            assertEquals(resp.body(), "", u + ": body");
        } else if (method.equals("DO_NOT_FOLLOW")) {
            assertNotEquals(resp.body(), GET_RESPONSE_BODY, u + ": body");
            assertNotEquals(resp.body(), REQUEST_BODY, u + ": body");
        } else if (code == 303) {
            assertEquals(resp.body(), GET_RESPONSE_BODY, u + ": body");
        } else {
            assertEquals(resp.body(), REQUEST_BODY, u + ": body");
        }
    }

    @AfterClass
    public void tearDown() {
        proxy = stop(proxy, DigestEchoServer.TunnelingProxy::stop);
        http1Server = stop(http1Server, HttpTestServer::stop);
        https1Server = stop(https1Server, HttpTestServer::stop);
        http2Server = stop(http2Server, HttpTestServer::stop);
        https2Server = stop(https2Server, HttpTestServer::stop);
        client = null;
        try {
            executor.awaitTermination(2000, TimeUnit.MILLISECONDS);
        } catch (Throwable x) {
        } finally {
            executor.shutdownNow();
        }
        try {
            clientexec.awaitTermination(2000, TimeUnit.MILLISECONDS);
        } catch (Throwable x) {
        } finally {
            clientexec.shutdownNow();
        }
        System.out.println("Teardown: done");
    }

    private interface Stoppable<T> { public void stop(T service) throws Exception; }

    static <T>  T stop(T service, Stoppable<T> stop) {
        try { if (service != null) stop.stop(service); } catch (Throwable x) { };
        return null;
    }

    static class HttpProxySelector extends ProxySelector {
        private static final List<Proxy> NO_PROXY = List.of(Proxy.NO_PROXY);
        private final List<Proxy> proxyList;
        HttpProxySelector(InetSocketAddress proxyAddress) {
            proxyList = List.of(new Proxy(Proxy.Type.HTTP, proxyAddress));
        }

        @Override
        public List<Proxy> select(URI uri) {
            // our proxy only supports tunneling
            if (uri.getScheme().equalsIgnoreCase("https")) {
                if (uri.getPath().contains("/proxy/")) {
                    return proxyList;
                }
            }
            return NO_PROXY;
        }

        @Override
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
            System.err.println("Connection to proxy failed: " + ioe);
            System.err.println("Proxy: " + sa);
            System.err.println("\tURI: " + uri);
            ioe.printStackTrace();
        }
    }

    public static class HttpTestRedirectHandler implements HttpTestHandler {
        static final AtomicLong respCounter = new AtomicLong();
        final String scheme;
        final HttpTestServer server;
        HttpTestRedirectHandler(String scheme, HttpTestServer server) {
            this.scheme = scheme;
            this.server = server;
        }

        @Override
        public void handle(HttpTestExchange t) throws IOException {
            try (InputStream is = t.getRequestBody()) {
                byte[] bytes = is.readAllBytes();
                URI u = t.getRequestURI();
                long responseID = Long.parseLong(u.getQuery().substring(2));
                String path = u.getPath();
                int i = path.lastIndexOf('/');
                String file = path.substring(i+1);
                String parent =  path.substring(0, i);
                int code = 200;
                if (file.equals("foo")) {
                    i = parent.lastIndexOf("/");
                    code = Integer.parseInt(parent.substring(i+1));
                }
                String response;
                if (code == 200) {
                    if (t.getRequestMethod().equals("GET")) {
                        if (bytes.length == 0) {
                            response = GET_RESPONSE_BODY;
                        } else {
                            response = new String(bytes, StandardCharsets.UTF_8);
                        }
                    } else if (t.getRequestMethod().equals("POST")) {
                        response = new String(bytes, StandardCharsets.UTF_8);
                    } else {
                        response = new String(bytes, StandardCharsets.UTF_8);
                    }
                } else if (code < 300 || code > 399) {
                    response = "Unexpected code: " + code;
                    code = 400;
                } else {
                    try {
                        URI reloc = new URI(scheme, server.serverAuthority(), parent + "/bar", u.getQuery(), null);
                        t.getResponseHeaders().addHeader("Location", reloc.toASCIIString());
                        if (code != 304) {
                            response = "Code: " + code;
                        } else response = null;
                    } catch (URISyntaxException x) {
                        x.printStackTrace();
                        x.printStackTrace(System.out);
                        code = 400;
                        response = x.toString();
                    }
                }

                System.out.println("Server " + t.getRequestURI() + " sending response " + responseID);
                System.out.println("code: " + code + " body: " + response);
                t.sendResponseHeaders(code, code == 304 ? 0: -1);
                if (code != 304) {
                    try (OutputStream os = t.getResponseBody()) {
                        bytes = response.getBytes(StandardCharsets.UTF_8);
                        os.write(bytes);
                        os.flush();
                    }
                } else {
                    bytes = new byte[0];
                }

                System.out.println("\tresp:" + responseID + ": wrote " + bytes.length + " bytes");
            } catch (Throwable e) {
                e.printStackTrace();
                e.printStackTrace(System.out);
                throw e;
            }
        }
    }

}