B5017051.java revision 14606:bc3775e25b52
1/*
2 * Copyright (c) 2005, 2016, 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 * @bug 5017051 6360774
27 * @modules jdk.httpserver
28 * @run main/othervm B5017051
29 * @summary Tests CR 5017051 & 6360774
30 */
31
32import java.net.*;
33import java.util.*;
34import java.io.*;
35import com.sun.net.httpserver.*;
36import java.util.concurrent.Executors;
37import java.util.concurrent.ExecutorService;
38
39/*
40 * Part 1:
41 *  First request sent to the http server will not have an "Authorization" header set and
42 *  the server will respond with a 401, but not until it has set a cookie in the response
43 *  headers. The subsequent request ( comes from HttpURLConnection's authentication retry )
44 *  will have the appropriate Authorization header and the servers context handler will be
45 *  invoked. The test passes only if the client (HttpURLConnection) has sent the cookie
46 *  in its second request that had been set via the first response from the server.
47 *
48 * Part 2:
49 *  Preload the CookieManager with a cookie. Make a http request that requires authentication
50 *  The cookie will be sent in the first request (without the Authorization header), the
51 *  server will respond with a 401 (from MyBasicAuthFilter) and the client will add the
52 *  appropriate Authorization header. This tests ensures that there is only one Cookie header
53 *  in the request that actually makes it to the Http servers context handler.
54 */
55
56public class B5017051
57{
58    com.sun.net.httpserver.HttpServer httpServer;
59    ExecutorService executorService;
60
61    public static void main(String[] args)
62    {
63        new B5017051();
64    }
65
66    public B5017051()
67    {
68        try {
69            startHttpServer();
70            doClient();
71        } catch (IOException ioe) {
72            System.err.println(ioe);
73        }
74    }
75
76    void doClient() {
77        java.net.Authenticator.setDefault(new MyAuthenticator());
78        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
79
80        try {
81            InetSocketAddress address = httpServer.getAddress();
82
83            // Part 1
84            URL url = new URL("http://" + address.getHostName() + ":" + address.getPort() + "/test/");
85            HttpURLConnection uc = (HttpURLConnection)url.openConnection();
86            int resp = uc.getResponseCode();
87            if (resp != 200)
88                throw new RuntimeException("Failed: Part 1, Response code is not 200");
89
90            System.out.println("Response code from Part 1 = 200 OK");
91
92            // Part 2
93            URL url2 = new URL("http://" + address.getHostName() + ":" + address.getPort() + "/test2/");
94
95            // can use the global CookieHandler used for the first test as the URL's are different
96            CookieHandler ch = CookieHandler.getDefault();
97            Map<String,List<String>> header = new HashMap<String,List<String>>();
98            List<String> values = new LinkedList<String>();
99            values.add("Test2Cookie=\"TEST2\"; path=\"/test2/\"");
100            header.put("Set-Cookie2", values);
101
102            // preload the CookieHandler with a cookie for our URL
103            // so that it will be sent during the first request
104            ch.put(url2.toURI(), header);
105
106            uc = (HttpURLConnection)url2.openConnection();
107            resp = uc.getResponseCode();
108            if (resp != 200)
109                throw new RuntimeException("Failed: Part 2, Response code is not 200");
110
111            System.out.println("Response code from Part 2 = 200 OK");
112
113
114        } catch (IOException e) {
115            e.printStackTrace();
116        } catch (URISyntaxException ue) {
117            ue.printStackTrace();
118        } finally {
119            httpServer.stop(1);
120            executorService.shutdown();
121        }
122    }
123
124    /**
125     * Http Server
126     */
127    public void startHttpServer() throws IOException {
128        httpServer = com.sun.net.httpserver.HttpServer.create(new InetSocketAddress(0), 0);
129
130        // create HttpServer context for Part 1.
131        HttpContext ctx = httpServer.createContext("/test/", new MyHandler());
132        ctx.setAuthenticator( new MyBasicAuthenticator("foo"));
133        // CookieFilter needs to be executed before Authenticator.
134        ctx.getFilters().add(0, new CookieFilter());
135
136        // create HttpServer context for Part 2.
137        HttpContext ctx2 = httpServer.createContext("/test2/", new MyHandler2());
138        ctx2.setAuthenticator( new MyBasicAuthenticator("foobar"));
139
140        executorService = Executors.newCachedThreadPool();
141        httpServer.setExecutor(executorService);
142        httpServer.start();
143    }
144
145    class MyHandler implements HttpHandler {
146        public void handle(HttpExchange t) throws IOException {
147            InputStream is = t.getRequestBody();
148            Headers reqHeaders = t.getRequestHeaders();
149            Headers resHeaders = t.getResponseHeaders();
150            while (is.read () != -1) ;
151            is.close();
152
153            if (!reqHeaders.containsKey("Authorization"))
154                t.sendResponseHeaders(400, -1);
155
156            List<String> cookies = reqHeaders.get("Cookie");
157            if (cookies != null) {
158                for (String str : cookies) {
159                    if (str.equals("Customer=WILE_E_COYOTE"))
160                        t.sendResponseHeaders(200, -1);
161                }
162            }
163            t.sendResponseHeaders(400, -1);
164        }
165    }
166
167    class MyHandler2 implements HttpHandler {
168        public void handle(HttpExchange t) throws IOException {
169            InputStream is = t.getRequestBody();
170            Headers reqHeaders = t.getRequestHeaders();
171            Headers resHeaders = t.getResponseHeaders();
172            while (is.read () != -1) ;
173            is.close();
174
175            if (!reqHeaders.containsKey("Authorization"))
176                t.sendResponseHeaders(400, -1);
177
178            List<String> cookies = reqHeaders.get("Cookie");
179
180            // there should only be one Cookie header
181            if (cookies != null && (cookies.size() == 1)) {
182                t.sendResponseHeaders(200, -1);
183            }
184            t.sendResponseHeaders(400, -1);
185        }
186    }
187
188    class MyAuthenticator extends java.net.Authenticator {
189        public PasswordAuthentication getPasswordAuthentication () {
190            return new PasswordAuthentication("tester", "passwd".toCharArray());
191        }
192    }
193
194    class MyBasicAuthenticator extends BasicAuthenticator
195    {
196        public MyBasicAuthenticator(String realm) {
197            super(realm);
198        }
199
200        public boolean checkCredentials (String username, String password) {
201            return username.equals("tester") && password.equals("passwd");
202        }
203    }
204
205    class CookieFilter extends Filter
206    {
207        public void doFilter(HttpExchange t, Chain chain) throws IOException
208        {
209            Headers resHeaders = t.getResponseHeaders();
210            Headers reqHeaders = t.getRequestHeaders();
211
212            if (!reqHeaders.containsKey("Authorization"))
213                resHeaders.set("Set-Cookie2", "Customer=\"WILE_E_COYOTE\"; path=\"/test/\"");
214
215            chain.doFilter(t);
216        }
217
218        public void destroy(HttpContext c) { }
219
220        public void init(HttpContext c) { }
221
222        public String description() {
223            return new String("Filter for setting a cookie for requests without an \"Authorization\" header.");
224        }
225    }
226}
227