Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/jdk17u
Path: blob/master/test/jdk/java/net/httpclient/ForbiddenHeadTest.java
66644 views
1
/*
2
* Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
24
/*
25
* @test
26
* @summary checks that receiving 403 for a HEAD request after
27
* 401/407 doesn't cause any unexpected behavior.
28
* @modules java.base/sun.net.www.http
29
* java.net.http/jdk.internal.net.http.common
30
* java.net.http/jdk.internal.net.http.frame
31
* java.net.http/jdk.internal.net.http.hpack
32
* java.logging
33
* jdk.httpserver
34
* java.base/sun.net.www.http
35
* java.base/sun.net.www
36
* java.base/sun.net
37
* @library /test/lib http2/server
38
* @build HttpServerAdapters DigestEchoServer Http2TestServer ForbiddenHeadTest
39
* @build jdk.test.lib.net.SimpleSSLContext
40
* @run testng/othervm
41
* -Djdk.http.auth.tunneling.disabledSchemes
42
* -Djdk.httpclient.HttpClient.log=headers,requests
43
* -Djdk.internal.httpclient.debug=true
44
* ForbiddenHeadTest
45
*/
46
47
import com.sun.net.httpserver.HttpServer;
48
import com.sun.net.httpserver.HttpsConfigurator;
49
import com.sun.net.httpserver.HttpsServer;
50
import jdk.test.lib.net.SimpleSSLContext;
51
import org.testng.ITestContext;
52
import org.testng.ITestResult;
53
import org.testng.SkipException;
54
import org.testng.annotations.AfterClass;
55
import org.testng.annotations.AfterTest;
56
import org.testng.annotations.BeforeMethod;
57
import org.testng.annotations.BeforeTest;
58
import org.testng.annotations.DataProvider;
59
import org.testng.annotations.Test;
60
61
import javax.net.ssl.SSLContext;
62
import java.io.IOException;
63
import java.io.InputStream;
64
import java.net.Authenticator;
65
import java.net.InetAddress;
66
import java.net.InetSocketAddress;
67
import java.net.PasswordAuthentication;
68
import java.net.Proxy;
69
import java.net.ProxySelector;
70
import java.net.SocketAddress;
71
import java.net.URI;
72
import java.net.http.HttpClient;
73
import java.net.http.HttpRequest;
74
import java.net.http.HttpResponse;
75
import java.net.http.HttpResponse.BodyHandlers;
76
import java.util.ArrayList;
77
import java.util.Arrays;
78
import java.util.List;
79
import java.util.Optional;
80
import java.util.concurrent.ConcurrentHashMap;
81
import java.util.concurrent.ConcurrentMap;
82
import java.util.concurrent.ExecutionException;
83
import java.util.concurrent.Executor;
84
import java.util.concurrent.Executors;
85
import java.util.concurrent.atomic.AtomicLong;
86
import java.util.concurrent.atomic.AtomicReference;
87
88
import static java.lang.System.err;
89
import static java.lang.System.out;
90
import static java.nio.charset.StandardCharsets.UTF_8;
91
import static org.testng.Assert.assertEquals;
92
import static org.testng.Assert.assertNotNull;
93
94
public class ForbiddenHeadTest implements HttpServerAdapters {
95
96
SSLContext sslContext;
97
HttpTestServer httpTestServer; // HTTP/1.1
98
HttpTestServer httpsTestServer; // HTTPS/1.1
99
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
100
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
101
DigestEchoServer.TunnelingProxy proxy;
102
DigestEchoServer.TunnelingProxy authproxy;
103
String httpURI;
104
String httpsURI;
105
String http2URI;
106
String https2URI;
107
HttpClient authClient;
108
HttpClient noAuthClient;
109
110
final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
111
static final long SLEEP_AFTER_TEST = 0; // milliseconds
112
static final int ITERATIONS = 3;
113
static final Executor executor = new TestExecutor(Executors.newCachedThreadPool());
114
static final ConcurrentMap<String, Throwable> FAILURES = new ConcurrentHashMap<>();
115
static volatile boolean tasksFailed;
116
static final AtomicLong serverCount = new AtomicLong();
117
static final AtomicLong clientCount = new AtomicLong();
118
static final long start = System.nanoTime();
119
public static String now() {
120
long now = System.nanoTime() - start;
121
long secs = now / 1000_000_000;
122
long mill = (now % 1000_000_000) / 1000_000;
123
long nan = now % 1000_000;
124
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);
125
}
126
127
static class TestExecutor implements Executor {
128
final AtomicLong tasks = new AtomicLong();
129
Executor executor;
130
TestExecutor(Executor executor) {
131
this.executor = executor;
132
}
133
134
@Override
135
public void execute(Runnable command) {
136
long id = tasks.incrementAndGet();
137
executor.execute(() -> {
138
try {
139
command.run();
140
} catch (Throwable t) {
141
tasksFailed = true;
142
out.printf(now() + "Task %s failed: %s%n", id, t);
143
err.printf(now() + "Task %s failed: %s%n", id, t);
144
FAILURES.putIfAbsent("Task " + id, t);
145
throw t;
146
}
147
});
148
}
149
}
150
151
protected boolean stopAfterFirstFailure() {
152
return Boolean.getBoolean("jdk.internal.httpclient.debug");
153
}
154
155
final AtomicReference<SkipException> skiptests = new AtomicReference<>();
156
void checkSkip() {
157
var skip = skiptests.get();
158
if (skip != null) throw skip;
159
}
160
static String name(ITestResult result) {
161
var params = result.getParameters();
162
return result.getName()
163
+ (params == null ? "()" : Arrays.toString(result.getParameters()));
164
}
165
166
@BeforeMethod
167
void beforeMethod(ITestContext context) {
168
if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {
169
if (skiptests.get() == null) {
170
SkipException skip = new SkipException("some tests failed");
171
skip.setStackTrace(new StackTraceElement[0]);
172
skiptests.compareAndSet(null, skip);
173
}
174
}
175
}
176
177
@AfterClass
178
static final void printFailedTests(ITestContext context) {
179
out.println("\n=========================");
180
try {
181
// Exceptions should already have been added to FAILURES
182
// var failed = context.getFailedTests().getAllResults().stream()
183
// .collect(Collectors.toMap(r -> name(r), ITestResult::getThrowable));
184
// FAILURES.putAll(failed);
185
186
out.printf("%n%sCreated %d servers and %d clients%n",
187
now(), serverCount.get(), clientCount.get());
188
if (FAILURES.isEmpty()) return;
189
out.println("Failed tests: ");
190
FAILURES.entrySet().forEach((e) -> {
191
out.printf("\t%s: %s%n", e.getKey(), e.getValue());
192
e.getValue().printStackTrace(out);
193
e.getValue().printStackTrace();
194
});
195
if (tasksFailed) {
196
out.println("WARNING: Some tasks failed");
197
}
198
} finally {
199
out.println("\n=========================\n");
200
}
201
}
202
203
static final int UNAUTHORIZED = 401;
204
static final int PROXY_UNAUTHORIZED = 407;
205
static final int FORBIDDEN = 403;
206
static final int HTTP_OK = 200;
207
static final String MESSAGE = "Unauthorized";
208
209
210
@DataProvider(name = "all")
211
public Object[][] allcases() {
212
List<Object[]> result = new ArrayList<>();
213
for (var client : List.of(authClient, noAuthClient)) {
214
for (boolean async : List.of(true, false)) {
215
for (int code : List.of(UNAUTHORIZED, PROXY_UNAUTHORIZED)) {
216
var srv = code == PROXY_UNAUTHORIZED ? "/proxy" : "/server";
217
for (var auth : List.of("/auth", "/noauth")) {
218
var pcode = code;
219
if (auth.equals("/noauth")) {
220
if (client == authClient) continue;
221
pcode = FORBIDDEN;
222
}
223
for (var uri : List.of(httpURI, httpsURI, http2URI, https2URI)) {
224
result.add(new Object[]{uri + srv + auth, pcode, async, client});
225
}
226
}
227
}
228
}
229
}
230
return result.toArray(new Object[0][0]);
231
}
232
233
static final AtomicLong requestCounter = new AtomicLong();
234
235
static final Authenticator authenticator = new Authenticator() {
236
@Override
237
protected PasswordAuthentication getPasswordAuthentication() {
238
return new PasswordAuthentication("arthur",new char[] {'d', 'e', 'n', 't'});
239
}
240
};
241
242
static final AtomicLong sleepCount = new AtomicLong();
243
244
@Test(dataProvider = "all")
245
void test(String uriString, int code, boolean async, HttpClient client) throws Throwable {
246
checkSkip();
247
var name = String.format("test(%s, %d, %s, %s)", uriString, code, async ? "async" : "sync",
248
client.authenticator().isPresent() ? "authClient" : "noAuthClient");
249
out.printf("%n---- starting %s ----%n", name);
250
assert client.authenticator().isPresent() ? client == authClient : client == noAuthClient;
251
uriString = uriString + "/ForbiddenTest";
252
for (int i=0; i<ITERATIONS; i++) {
253
if (ITERATIONS > 1) out.printf("---- ITERATION %d%n",i);
254
try {
255
doTest(uriString, code, async, client);
256
long count = sleepCount.incrementAndGet();
257
System.err.println(now() + " Sleeping: " + count);
258
Thread.sleep(SLEEP_AFTER_TEST);
259
System.err.println(now() + " Waking up: " + count);
260
} catch (Throwable x) {
261
FAILURES.putIfAbsent(name, x);
262
throw x;
263
}
264
}
265
}
266
267
static String authHeaderName(int code) {
268
return switch (code) {
269
case UNAUTHORIZED -> "WWW-Authenticate";
270
case PROXY_UNAUTHORIZED -> "Proxy-Authenticate";
271
default -> null;
272
};
273
}
274
275
private void doTest(String uriString, int code, boolean async, HttpClient client) throws Throwable {
276
URI uri = URI.create(uriString);
277
278
HttpRequest.Builder requestBuilder = HttpRequest
279
.newBuilder(uri)
280
.method("HEAD", HttpRequest.BodyPublishers.noBody());
281
282
HttpRequest request = requestBuilder.build();
283
out.println("Initial request: " + request.uri());
284
285
String header = authHeaderName(code);
286
// the request is expected to return 403 Forbidden if the client is authenticated,
287
// or the server doesn't require authentication, 401 or 407 otherwise.
288
boolean forbidden = client.authenticator().isPresent() || code == FORBIDDEN;
289
290
HttpResponse<String> response = null;
291
if (async) {
292
response = client.send(request, BodyHandlers.ofString());
293
} else {
294
try {
295
response = client.sendAsync(request, BodyHandlers.ofString()).get();
296
} catch (ExecutionException ex) {
297
throw ex.getCause();
298
}
299
}
300
301
String prefix = uriString.contains("/proxy/") ? "Proxy-" : "WWW-";
302
String expectedValue;
303
if (forbidden) {
304
// The message body is generated by the server, after authentication was
305
// successful.
306
expectedValue = prefix + "FORBIDDEN";
307
} else if (uriString.contains("/proxy/") && uri.getScheme().equalsIgnoreCase("https")) {
308
// In that case the tunnelling proxy itself is expected to return 407,
309
// and the message will have no body (since the CONNECT request fails).
310
assert code == PROXY_UNAUTHORIZED;
311
expectedValue = null;
312
} else {
313
// the message body is generated by our fake server pretending to be
314
// a proxy.
315
expectedValue = prefix + MESSAGE;
316
}
317
318
319
out.println(" Got response: " + response);
320
assertEquals(response.statusCode(), forbidden? FORBIDDEN : code);
321
assertEquals(response.body(), expectedValue == null ? null : "");
322
assertEquals(response.headers().firstValue("X-value"), Optional.ofNullable(expectedValue));
323
// when the CONNECT request fails, its body is discarded - but
324
// the response header may still contain its content length.
325
// don't check content length in that case.
326
if (expectedValue != null) {
327
String clen = String.valueOf(expectedValue.getBytes(UTF_8).length);
328
assertEquals(response.headers().firstValue("Content-Length"), Optional.of(clen));
329
}
330
331
}
332
333
// -- Infrastructure
334
335
@BeforeTest
336
public void setup() throws Exception {
337
sslContext = new SimpleSSLContext().get();
338
if (sslContext == null)
339
throw new AssertionError("Unexpected null sslContext");
340
341
InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
342
343
httpTestServer = HttpTestServer.of(HttpServer.create(sa, 0));
344
httpTestServer.addHandler(new UnauthorizedHandler(), "/http1/");
345
httpTestServer.addHandler(new UnauthorizedHandler(), "/http2/proxy/");
346
httpURI = "http://" + httpTestServer.serverAuthority() + "/http1";
347
HttpsServer httpsServer = HttpsServer.create(sa, 0);
348
httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
349
httpsTestServer = HttpTestServer.of(httpsServer);
350
httpsTestServer.addHandler(new UnauthorizedHandler(),"/https1/");
351
httpsURI = "https://" + httpsTestServer.serverAuthority() + "/https1";
352
353
http2TestServer = HttpTestServer.of(new Http2TestServer("localhost", false, 0));
354
http2TestServer.addHandler(new UnauthorizedHandler(), "/http2/");
355
http2URI = "http://" + http2TestServer.serverAuthority() + "/http2";
356
https2TestServer = HttpTestServer.of(new Http2TestServer("localhost", true, sslContext));
357
https2TestServer.addHandler(new UnauthorizedHandler(), "/https2/");
358
https2URI = "https://" + https2TestServer.serverAuthority() + "/https2";
359
360
proxy = DigestEchoServer.createHttpsProxyTunnel(DigestEchoServer.HttpAuthSchemeType.NONE);
361
authproxy = DigestEchoServer.createHttpsProxyTunnel(DigestEchoServer.HttpAuthSchemeType.BASIC);
362
363
authClient = TRACKER.track(HttpClient.newBuilder()
364
.proxy(TestProxySelector.of(proxy, authproxy, httpTestServer))
365
.sslContext(sslContext)
366
.executor(executor)
367
.authenticator(authenticator)
368
.build());
369
clientCount.incrementAndGet();
370
371
noAuthClient = TRACKER.track(HttpClient.newBuilder()
372
.proxy(TestProxySelector.of(proxy, authproxy, httpTestServer))
373
.sslContext(sslContext)
374
.executor(executor)
375
.build());
376
clientCount.incrementAndGet();
377
378
httpTestServer.start();
379
serverCount.incrementAndGet();
380
httpsTestServer.start();
381
serverCount.incrementAndGet();
382
http2TestServer.start();
383
serverCount.incrementAndGet();
384
https2TestServer.start();
385
serverCount.incrementAndGet();
386
}
387
388
@AfterTest
389
public void teardown() throws Exception {
390
authClient = noAuthClient = null;
391
Thread.sleep(100);
392
AssertionError fail = TRACKER.check(500);
393
394
proxy.stop();
395
authproxy.stop();
396
httpTestServer.stop();
397
httpsTestServer.stop();
398
http2TestServer.stop();
399
https2TestServer.stop();
400
}
401
402
static class TestProxySelector extends ProxySelector {
403
final DigestEchoServer.TunnelingProxy proxy;
404
final DigestEchoServer.TunnelingProxy authproxy;
405
final HttpTestServer plain;
406
private TestProxySelector(DigestEchoServer.TunnelingProxy proxy,
407
DigestEchoServer.TunnelingProxy authproxy,
408
HttpTestServer plain) {
409
this.proxy = proxy;
410
this.authproxy = authproxy;
411
this.plain = plain;
412
}
413
@Override
414
public List<Proxy> select(URI uri) {
415
String path = uri.getPath();
416
out.println("Selecting proxy for: " + uri);
417
if (path.contains("/proxy/")) {
418
if (path.contains("/http1/")) {
419
// Simple proxying - in our test the server pretends
420
// to be the proxy.
421
System.out.print("PROXY is server for " + uri);
422
return List.of(new Proxy(Proxy.Type.HTTP,
423
new InetSocketAddress(uri.getHost(), uri.getPort())));
424
} else if (path.contains("/http2/")) {
425
// HTTP/2 is downgraded to HTTP/1.1 if there is a proxy
426
System.out.print("PROXY is plain server for " + uri);
427
return List.of(new Proxy(Proxy.Type.HTTP, plain.getAddress()));
428
} else {
429
// Both HTTPS or HTTPS/2 require tunnelling
430
var p = path.contains("/auth/") ? authproxy : proxy;
431
if (p == authproxy) {
432
out.println("PROXY is authenticating tunneling proxy for " + uri);
433
} else {
434
out.println("PROXY is plain tunneling proxy for " + uri);
435
}
436
return List.of(new Proxy(Proxy.Type.HTTP, p.getProxyAddress()));
437
}
438
}
439
System.out.print("NO_PROXY for " + uri);
440
return List.of(Proxy.NO_PROXY);
441
}
442
@Override
443
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
444
System.err.printf("Connect failed for: uri=\"%s\", sa=\"%s\", ioe=%s%n", uri, sa, ioe);
445
}
446
public static TestProxySelector of(DigestEchoServer.TunnelingProxy proxy,
447
DigestEchoServer.TunnelingProxy authproxy,
448
HttpTestServer plain) {
449
return new TestProxySelector(proxy, authproxy, plain);
450
}
451
}
452
453
static class UnauthorizedHandler implements HttpTestHandler {
454
455
@Override
456
public void handle(HttpTestExchange t) throws IOException {
457
readAllRequestData(t); // shouldn't be any
458
String method = t.getRequestMethod();
459
String path = t.getRequestURI().getPath();
460
HttpTestRequestHeaders reqh = t.getRequestHeaders();
461
HttpTestResponseHeaders rsph = t.getResponseHeaders();
462
463
String xValue;
464
boolean noAuthRequired = path.contains("/noauth/");
465
boolean authenticated = path.contains("/server/") && reqh.containsKey("Authorization")
466
|| path.contains("/proxy/") && reqh.containsKey("Proxy-Authorization")
467
|| path.contains("/proxy/") && (path.contains("/https1/") || path.contains("/https2/"));
468
String srv = path.contains("/proxy/") ? "proxy" : "server";
469
String prefix = path.contains("/proxy/") ? "Proxy-" : "WWW-";
470
int authcode = path.contains("/proxy/") ? PROXY_UNAUTHORIZED : UNAUTHORIZED;
471
int code = (authenticated || noAuthRequired) ? FORBIDDEN : authcode;
472
if (authenticated || noAuthRequired) {
473
xValue = prefix + "FORBIDDEN";
474
} else {
475
xValue = prefix + MESSAGE;
476
rsph.addHeader(prefix + "Authenticate", "Basic realm=\"earth\", charset=\"UTF-8\"");
477
}
478
479
t.getResponseHeaders().addHeader("X-value", xValue);
480
t.getResponseHeaders().addHeader("Content-Length", String.valueOf(xValue.getBytes(UTF_8).length));
481
t.sendResponseHeaders(code, 0);
482
}
483
}
484
485
static void readAllRequestData(HttpTestExchange t) throws IOException {
486
try (InputStream is = t.getRequestBody()) {
487
is.readAllBytes();
488
}
489
}
490
}
491
492