Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/java/net/httpclient/ForbiddenHeadTest.java
41149 views
1
/*
2
* Copyright (c) 2020, 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.annotations.AfterClass;
53
import org.testng.annotations.AfterTest;
54
import org.testng.annotations.BeforeMethod;
55
import org.testng.annotations.BeforeTest;
56
import org.testng.annotations.DataProvider;
57
import org.testng.annotations.Test;
58
59
import javax.net.ssl.SSLContext;
60
import java.io.IOException;
61
import java.io.InputStream;
62
import java.net.Authenticator;
63
import java.net.InetAddress;
64
import java.net.InetSocketAddress;
65
import java.net.PasswordAuthentication;
66
import java.net.Proxy;
67
import java.net.ProxySelector;
68
import java.net.SocketAddress;
69
import java.net.URI;
70
import java.net.http.HttpClient;
71
import java.net.http.HttpRequest;
72
import java.net.http.HttpResponse;
73
import java.net.http.HttpResponse.BodyHandlers;
74
import java.util.ArrayList;
75
import java.util.List;
76
import java.util.Optional;
77
import java.util.concurrent.ConcurrentHashMap;
78
import java.util.concurrent.ConcurrentMap;
79
import java.util.concurrent.ExecutionException;
80
import java.util.concurrent.Executor;
81
import java.util.concurrent.Executors;
82
import java.util.concurrent.atomic.AtomicLong;
83
84
import static java.lang.System.err;
85
import static java.lang.System.out;
86
import static java.nio.charset.StandardCharsets.UTF_8;
87
import static org.testng.Assert.assertEquals;
88
import static org.testng.Assert.assertNotNull;
89
90
public class ForbiddenHeadTest implements HttpServerAdapters {
91
92
SSLContext sslContext;
93
HttpTestServer httpTestServer; // HTTP/1.1
94
HttpTestServer httpsTestServer; // HTTPS/1.1
95
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
96
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
97
DigestEchoServer.TunnelingProxy proxy;
98
DigestEchoServer.TunnelingProxy authproxy;
99
String httpURI;
100
String httpsURI;
101
String http2URI;
102
String https2URI;
103
HttpClient authClient;
104
HttpClient noAuthClient;
105
106
final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
107
static final long SLEEP_AFTER_TEST = 0; // milliseconds
108
static final int ITERATIONS = 3;
109
static final Executor executor = new TestExecutor(Executors.newCachedThreadPool());
110
static final ConcurrentMap<String, Throwable> FAILURES = new ConcurrentHashMap<>();
111
static volatile boolean tasksFailed;
112
static final AtomicLong serverCount = new AtomicLong();
113
static final AtomicLong clientCount = new AtomicLong();
114
static final long start = System.nanoTime();
115
public static String now() {
116
long now = System.nanoTime() - start;
117
long secs = now / 1000_000_000;
118
long mill = (now % 1000_000_000) / 1000_000;
119
long nan = now % 1000_000;
120
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);
121
}
122
123
static class TestExecutor implements Executor {
124
final AtomicLong tasks = new AtomicLong();
125
Executor executor;
126
TestExecutor(Executor executor) {
127
this.executor = executor;
128
}
129
130
@Override
131
public void execute(Runnable command) {
132
long id = tasks.incrementAndGet();
133
executor.execute(() -> {
134
try {
135
command.run();
136
} catch (Throwable t) {
137
tasksFailed = true;
138
out.printf(now() + "Task %s failed: %s%n", id, t);
139
err.printf(now() + "Task %s failed: %s%n", id, t);
140
FAILURES.putIfAbsent("Task " + id, t);
141
throw t;
142
}
143
});
144
}
145
}
146
147
protected boolean stopAfterFirstFailure() {
148
return Boolean.getBoolean("jdk.internal.httpclient.debug");
149
}
150
151
@BeforeMethod
152
void beforeMethod(ITestContext context) {
153
if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {
154
throw new RuntimeException("some tests failed");
155
}
156
}
157
158
@AfterClass
159
static final void printFailedTests() {
160
out.println("\n=========================");
161
try {
162
out.printf("%n%sCreated %d servers and %d clients%n",
163
now(), serverCount.get(), clientCount.get());
164
if (FAILURES.isEmpty()) return;
165
out.println("Failed tests: ");
166
FAILURES.entrySet().forEach((e) -> {
167
out.printf("\t%s: %s%n", e.getKey(), e.getValue());
168
e.getValue().printStackTrace(out);
169
e.getValue().printStackTrace();
170
});
171
if (tasksFailed) {
172
out.println("WARNING: Some tasks failed");
173
}
174
} finally {
175
out.println("\n=========================\n");
176
}
177
}
178
179
static final int UNAUTHORIZED = 401;
180
static final int PROXY_UNAUTHORIZED = 407;
181
static final int FORBIDDEN = 403;
182
static final int HTTP_OK = 200;
183
static final String MESSAGE = "Unauthorized";
184
185
186
@DataProvider(name = "all")
187
public Object[][] allcases() {
188
List<Object[]> result = new ArrayList<>();
189
for (var client : List.of(authClient, noAuthClient)) {
190
for (boolean async : List.of(true, false)) {
191
for (int code : List.of(UNAUTHORIZED, PROXY_UNAUTHORIZED)) {
192
var srv = code == PROXY_UNAUTHORIZED ? "/proxy" : "/server";
193
for (var auth : List.of("/auth", "/noauth")) {
194
var pcode = code;
195
if (auth.equals("/noauth")) {
196
if (client == authClient) continue;
197
pcode = FORBIDDEN;
198
}
199
for (var uri : List.of(httpURI, httpsURI, http2URI, https2URI)) {
200
result.add(new Object[]{uri + srv + auth, pcode, async, client});
201
}
202
}
203
}
204
}
205
}
206
return result.toArray(new Object[0][0]);
207
}
208
209
static final AtomicLong requestCounter = new AtomicLong();
210
211
static final Authenticator authenticator = new Authenticator() {
212
@Override
213
protected PasswordAuthentication getPasswordAuthentication() {
214
return new PasswordAuthentication("arthur",new char[] {'d', 'e', 'n', 't'});
215
}
216
};
217
218
static final AtomicLong sleepCount = new AtomicLong();
219
220
@Test(dataProvider = "all")
221
void test(String uriString, int code, boolean async, HttpClient client) throws Throwable {
222
var name = String.format("test(%s, %d, %s, %s)", uriString, code, async ? "async" : "sync",
223
client.authenticator().isPresent() ? "authClient" : "noAuthClient");
224
out.printf("%n---- starting %s ----%n", name);
225
assert client.authenticator().isPresent() ? client == authClient : client == noAuthClient;
226
uriString = uriString + "/ForbiddenTest";
227
for (int i=0; i<ITERATIONS; i++) {
228
if (ITERATIONS > 1) out.printf("---- ITERATION %d%n",i);
229
try {
230
doTest(uriString, code, async, client);
231
long count = sleepCount.incrementAndGet();
232
System.err.println(now() + " Sleeping: " + count);
233
Thread.sleep(SLEEP_AFTER_TEST);
234
System.err.println(now() + " Waking up: " + count);
235
} catch (Throwable x) {
236
FAILURES.putIfAbsent(name, x);
237
throw x;
238
}
239
}
240
}
241
242
static String authHeaderName(int code) {
243
return switch (code) {
244
case UNAUTHORIZED -> "WWW-Authenticate";
245
case PROXY_UNAUTHORIZED -> "Proxy-Authenticate";
246
default -> null;
247
};
248
}
249
250
private void doTest(String uriString, int code, boolean async, HttpClient client) throws Throwable {
251
URI uri = URI.create(uriString);
252
253
HttpRequest.Builder requestBuilder = HttpRequest
254
.newBuilder(uri)
255
.method("HEAD", HttpRequest.BodyPublishers.noBody());
256
257
HttpRequest request = requestBuilder.build();
258
out.println("Initial request: " + request.uri());
259
260
String header = authHeaderName(code);
261
// the request is expected to return 403 Forbidden if the client is authenticated,
262
// or the server doesn't require authentication, 401 or 407 otherwise.
263
boolean forbidden = client.authenticator().isPresent() || code == FORBIDDEN;
264
265
HttpResponse<String> response = null;
266
if (async) {
267
response = client.send(request, BodyHandlers.ofString());
268
} else {
269
try {
270
response = client.sendAsync(request, BodyHandlers.ofString()).get();
271
} catch (ExecutionException ex) {
272
throw ex.getCause();
273
}
274
}
275
276
String prefix = uriString.contains("/proxy/") ? "Proxy-" : "WWW-";
277
String expectedValue;
278
if (forbidden) {
279
// The message body is generated by the server, after authentication was
280
// successful.
281
expectedValue = prefix + "FORBIDDEN";
282
} else if (uriString.contains("/proxy/") && uri.getScheme().equalsIgnoreCase("https")) {
283
// In that case the tunnelling proxy itself is expected to return 407,
284
// and the message will have no body (since the CONNECT request fails).
285
assert code == PROXY_UNAUTHORIZED;
286
expectedValue = null;
287
} else {
288
// the message body is generated by our fake server pretending to be
289
// a proxy.
290
expectedValue = prefix + MESSAGE;
291
}
292
293
294
out.println(" Got response: " + response);
295
assertEquals(response.statusCode(), forbidden? FORBIDDEN : code);
296
assertEquals(response.body(), expectedValue == null ? null : "");
297
assertEquals(response.headers().firstValue("X-value"), Optional.ofNullable(expectedValue));
298
// when the CONNECT request fails, its body is discarded - but
299
// the response header may still contain its content length.
300
// don't check content length in that case.
301
if (expectedValue != null) {
302
String clen = String.valueOf(expectedValue.getBytes(UTF_8).length);
303
assertEquals(response.headers().firstValue("Content-Length"), Optional.of(clen));
304
}
305
306
}
307
308
// -- Infrastructure
309
310
@BeforeTest
311
public void setup() throws Exception {
312
sslContext = new SimpleSSLContext().get();
313
if (sslContext == null)
314
throw new AssertionError("Unexpected null sslContext");
315
316
InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
317
318
httpTestServer = HttpTestServer.of(HttpServer.create(sa, 0));
319
httpTestServer.addHandler(new UnauthorizedHandler(), "/http1/");
320
httpTestServer.addHandler(new UnauthorizedHandler(), "/http2/proxy/");
321
httpURI = "http://" + httpTestServer.serverAuthority() + "/http1";
322
HttpsServer httpsServer = HttpsServer.create(sa, 0);
323
httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
324
httpsTestServer = HttpTestServer.of(httpsServer);
325
httpsTestServer.addHandler(new UnauthorizedHandler(),"/https1/");
326
httpsURI = "https://" + httpsTestServer.serverAuthority() + "/https1";
327
328
http2TestServer = HttpTestServer.of(new Http2TestServer("localhost", false, 0));
329
http2TestServer.addHandler(new UnauthorizedHandler(), "/http2/");
330
http2URI = "http://" + http2TestServer.serverAuthority() + "/http2";
331
https2TestServer = HttpTestServer.of(new Http2TestServer("localhost", true, sslContext));
332
https2TestServer.addHandler(new UnauthorizedHandler(), "/https2/");
333
https2URI = "https://" + https2TestServer.serverAuthority() + "/https2";
334
335
proxy = DigestEchoServer.createHttpsProxyTunnel(DigestEchoServer.HttpAuthSchemeType.NONE);
336
authproxy = DigestEchoServer.createHttpsProxyTunnel(DigestEchoServer.HttpAuthSchemeType.BASIC);
337
338
authClient = TRACKER.track(HttpClient.newBuilder()
339
.proxy(TestProxySelector.of(proxy, authproxy, httpTestServer))
340
.sslContext(sslContext)
341
.executor(executor)
342
.authenticator(authenticator)
343
.build());
344
clientCount.incrementAndGet();
345
346
noAuthClient = TRACKER.track(HttpClient.newBuilder()
347
.proxy(TestProxySelector.of(proxy, authproxy, httpTestServer))
348
.sslContext(sslContext)
349
.executor(executor)
350
.build());
351
clientCount.incrementAndGet();
352
353
httpTestServer.start();
354
serverCount.incrementAndGet();
355
httpsTestServer.start();
356
serverCount.incrementAndGet();
357
http2TestServer.start();
358
serverCount.incrementAndGet();
359
https2TestServer.start();
360
serverCount.incrementAndGet();
361
}
362
363
@AfterTest
364
public void teardown() throws Exception {
365
authClient = noAuthClient = null;
366
Thread.sleep(100);
367
AssertionError fail = TRACKER.check(500);
368
369
proxy.stop();
370
authproxy.stop();
371
httpTestServer.stop();
372
httpsTestServer.stop();
373
http2TestServer.stop();
374
https2TestServer.stop();
375
}
376
377
static class TestProxySelector extends ProxySelector {
378
final DigestEchoServer.TunnelingProxy proxy;
379
final DigestEchoServer.TunnelingProxy authproxy;
380
final HttpTestServer plain;
381
private TestProxySelector(DigestEchoServer.TunnelingProxy proxy,
382
DigestEchoServer.TunnelingProxy authproxy,
383
HttpTestServer plain) {
384
this.proxy = proxy;
385
this.authproxy = authproxy;
386
this.plain = plain;
387
}
388
@Override
389
public List<Proxy> select(URI uri) {
390
String path = uri.getPath();
391
out.println("Selecting proxy for: " + uri);
392
if (path.contains("/proxy/")) {
393
if (path.contains("/http1/")) {
394
// Simple proxying - in our test the server pretends
395
// to be the proxy.
396
System.out.print("PROXY is server for " + uri);
397
return List.of(new Proxy(Proxy.Type.HTTP,
398
new InetSocketAddress(uri.getHost(), uri.getPort())));
399
} else if (path.contains("/http2/")) {
400
// HTTP/2 is downgraded to HTTP/1.1 if there is a proxy
401
System.out.print("PROXY is plain server for " + uri);
402
return List.of(new Proxy(Proxy.Type.HTTP, plain.getAddress()));
403
} else {
404
// Both HTTPS or HTTPS/2 require tunnelling
405
var p = path.contains("/auth/") ? authproxy : proxy;
406
if (p == authproxy) {
407
out.println("PROXY is authenticating tunneling proxy for " + uri);
408
} else {
409
out.println("PROXY is plain tunneling proxy for " + uri);
410
}
411
return List.of(new Proxy(Proxy.Type.HTTP, p.getProxyAddress()));
412
}
413
}
414
System.out.print("NO_PROXY for " + uri);
415
return List.of(Proxy.NO_PROXY);
416
}
417
@Override
418
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
419
System.err.printf("Connect failed for: uri=\"%s\", sa=\"%s\", ioe=%s%n", uri, sa, ioe);
420
}
421
public static TestProxySelector of(DigestEchoServer.TunnelingProxy proxy,
422
DigestEchoServer.TunnelingProxy authproxy,
423
HttpTestServer plain) {
424
return new TestProxySelector(proxy, authproxy, plain);
425
}
426
}
427
428
static class UnauthorizedHandler implements HttpTestHandler {
429
430
@Override
431
public void handle(HttpTestExchange t) throws IOException {
432
readAllRequestData(t); // shouldn't be any
433
String method = t.getRequestMethod();
434
String path = t.getRequestURI().getPath();
435
HttpTestRequestHeaders reqh = t.getRequestHeaders();
436
HttpTestResponseHeaders rsph = t.getResponseHeaders();
437
438
String xValue;
439
boolean noAuthRequired = path.contains("/noauth/");
440
boolean authenticated = path.contains("/server/") && reqh.containsKey("Authorization")
441
|| path.contains("/proxy/") && reqh.containsKey("Proxy-Authorization")
442
|| path.contains("/proxy/") && (path.contains("/https1/") || path.contains("/https2/"));
443
String srv = path.contains("/proxy/") ? "proxy" : "server";
444
String prefix = path.contains("/proxy/") ? "Proxy-" : "WWW-";
445
int authcode = path.contains("/proxy/") ? PROXY_UNAUTHORIZED : UNAUTHORIZED;
446
int code = (authenticated || noAuthRequired) ? FORBIDDEN : authcode;
447
if (authenticated || noAuthRequired) {
448
xValue = prefix + "FORBIDDEN";
449
} else {
450
xValue = prefix + MESSAGE;
451
rsph.addHeader(prefix + "Authenticate", "Basic realm=\"earth\", charset=\"UTF-8\"");
452
}
453
454
t.getResponseHeaders().addHeader("X-value", xValue);
455
t.getResponseHeaders().addHeader("Content-Length", String.valueOf(xValue.getBytes(UTF_8).length));
456
t.sendResponseHeaders(code, 0);
457
}
458
}
459
460
static void readAllRequestData(HttpTestExchange t) throws IOException {
461
try (InputStream is = t.getRequestBody()) {
462
is.readAllBytes();
463
}
464
}
465
}
466
467