Path: blob/master/test/jdk/java/net/CookieHandler/CookieManagerTest.java
41149 views
/*1* Copyright (c) 2005, 2019, 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 Unit test for java.net.CookieManager26* @bug 6244040 7150552 705186227* @modules jdk.httpserver28* java.logging29* @run main/othervm -ea -esa CookieManagerTest30* @author Edward Wang31*/3233import com.sun.net.httpserver.*;34import java.util.Collections;35import java.util.LinkedList;36import java.util.List;37import java.io.IOException;38import java.net.*;39import java.util.logging.Level;40import java.util.logging.Logger;41import static java.net.Proxy.NO_PROXY;4243public class CookieManagerTest {4445static CookieTransactionHandler httpTrans;46static HttpServer server;4748static final String hostAddress = getAddr();4950/** Returns an IP literal suitable for use by the test. */51static String getAddr() {52try {53InetAddress lh = InetAddress.getLocalHost();54System.out.println("Trying: " + lh);55if (lh.isReachable(5_000)) {56System.out.println("Using: " + lh);57return lh.getHostAddress();58}59} catch (IOException x) {60System.out.println("Debug: caught:" + x);61}62InetAddress loopback = InetAddress.getLoopbackAddress();63System.out.println("Using: \"" + loopback.getHostAddress() + "\"");64return loopback.getHostAddress();65}6667public static void main(String[] args) throws Exception {68// logs everything...69Logger root = Logger.getLogger("");70root.setLevel(Level.ALL);71root.getHandlers()[0].setLevel(Level.ALL);7273startHttpServer();74makeHttpCall();7576if (httpTrans.badRequest) {77throw new RuntimeException("Test failed : bad cookie header");78}79checkCookiePolicy();80}8182public static void startHttpServer() throws IOException {83httpTrans = new CookieTransactionHandler();84server = HttpServer.create(new InetSocketAddress(hostAddress, 0), 0);85server.createContext("/", httpTrans);86server.start();87}8889/*90* Checks if CookiePolicy.ACCEPT_ORIGINAL_SERVER#shouldAccept()91* returns false for null arguments92*/93private static void checkCookiePolicy() throws Exception {94CookiePolicy cp = CookiePolicy.ACCEPT_ORIGINAL_SERVER;95boolean retVal;96retVal = cp.shouldAccept(null, null);97checkValue(retVal);98retVal = cp.shouldAccept(null, new HttpCookie("CookieName", "CookieVal"));99checkValue(retVal);100retVal = cp.shouldAccept((new URL("http", "localhost", 2345, "/")).toURI(),101null);102checkValue(retVal);103}104105private static void checkValue(boolean val) {106if (val)107throw new RuntimeException("Return value is not false!");108}109110public static void makeHttpCall() throws IOException {111try {112int port = server.getAddress().getPort();113System.out.println("http server listenining on: " + port);114115// install CookieManager to use116CookieHandler.setDefault(new CookieManager());117118for (int i = 0; i < CookieTransactionHandler.testCount; i++) {119System.out.println("====== CookieManager test " + (i+1)120+ " ======");121((CookieManager)CookieHandler.getDefault())122.setCookiePolicy(CookieTransactionHandler.testPolicies[i]);123((CookieManager)CookieHandler.getDefault())124.getCookieStore().removeAll();125URL url = new URL("http" ,126hostAddress,127server.getAddress().getPort(),128CookieTransactionHandler.testCases[i][0]129.serverPath);130System.out.println("Requesting " + url);131HttpURLConnection uc = (HttpURLConnection)url.openConnection(NO_PROXY);132uc.getResponseCode();133uc.disconnect();134}135} finally {136server.stop(0);137}138}139}140141class CookieTransactionHandler implements HttpHandler {142143private int testcaseDone = 0;144private int testDone = 0;145146public static boolean badRequest = false;147// the main test control logic will also loop exactly this number148// to send http request149public static final int testCount = 6;150151@Override152public void handle(HttpExchange exchange) throws IOException {153if (testDone < testCases[testcaseDone].length) {154// still have other tests to run,155// check the Cookie header and then redirect it156if (testDone > 0) checkRequest(exchange.getRequestHeaders());157exchange.getResponseHeaders().add("Location",158testCases[testcaseDone][testDone].serverPath);159exchange.getResponseHeaders()160.add(testCases[testcaseDone][testDone].headerToken,161testCases[testcaseDone][testDone].cookieToSend);162exchange.sendResponseHeaders(302, -1);163testDone++;164} else {165// the last test of this test case166if (testDone > 0) checkRequest(exchange.getRequestHeaders());167testcaseDone++;168testDone = 0;169exchange.sendResponseHeaders(200, -1);170}171exchange.close();172}173174private static String trim(String s) {175StringBuilder sb = new StringBuilder();176for (int i=0; i<s.length(); i++) {177char c = s.charAt(i);178if (!Character.isWhitespace(c))179sb.append(c);180}181return sb.toString();182}183184private static boolean cookieEquals(String s1, String s2) {185s1 = trim(s1);186s2 = trim(s2);187String[] s1a = s1.split(";");188String[] s2a = s2.split(";");189List<String> l1 = new LinkedList(List.of(s1a));190List<String> l2 = new LinkedList(List.of(s2a));191Collections.sort(l1);192Collections.sort(l2);193int i = 0;194for (String s : l1) {195if (!s.equals(l2.get(i++))) {196return false;197}198}199return true;200}201202private void checkRequest(Headers hdrs) {203204assert testDone > 0;205String cookieHeader = hdrs.getFirst("Cookie");206if (cookieHeader != null && cookieEquals(207cookieHeader, testCases[testcaseDone][testDone-1].cookieToRecv))208{209System.out.printf("%15s %s\n", "PASSED:", cookieHeader);210} else {211System.out.printf("%15s %s\n", "FAILED:", cookieHeader);212System.out.printf("%15s %s\n\n", "should be:",213testCases[testcaseDone][testDone-1].cookieToRecv);214badRequest = true;215}216}217218// test cases219public static class CookieTestCase {220public String headerToken;221public String cookieToSend;222public String cookieToRecv;223public String serverPath;224225public CookieTestCase(String h, String cts, String ctr, String sp) {226headerToken = h;227cookieToSend = cts;228cookieToRecv = ctr;229serverPath = sp;230}231};232233/*234* these two must match each other,235* i.e. testCases.length == testPolicies.length236*/237238// the test cases to run; each test case may contain multiple roundtrips239public static CookieTestCase[][] testCases = null;240// indicates what CookiePolicy to use with each test cases241public static CookiePolicy[] testPolicies = null;242243CookieTransactionHandler() {244testCases = new CookieTestCase[testCount][];245testPolicies = new CookiePolicy[testCount];246247String localHostAddr = CookieManagerTest.hostAddress;248249int count = 0;250251// an http session with Netscape cookies exchanged252testPolicies[count] = CookiePolicy.ACCEPT_ORIGINAL_SERVER;253testCases[count++] = new CookieTestCase[]{254new CookieTestCase("Set-Cookie",255"CUSTOMER=WILE:BOB; " +256"path=/; expires=Sat, 09-Nov-2030 23:12:40 GMT;" + "domain=." +257localHostAddr,258"CUSTOMER=WILE:BOB",259"/"260),261new CookieTestCase("Set-Cookie",262"PART_NUMBER=ROCKET_LAUNCHER_0001; path=/;" + "domain=." + localHostAddr,263"CUSTOMER=WILE:BOB; PART_NUMBER=ROCKET_LAUNCHER_0001",264"/"265),266new CookieTestCase("Set-Cookie",267"SHIPPING=FEDEX; path=/foo;" + "domain=." + localHostAddr,268"CUSTOMER=WILE:BOB; PART_NUMBER=ROCKET_LAUNCHER_0001",269"/"270),271new CookieTestCase("Set-Cookie",272"SHIPPING=FEDEX; path=/foo;" + "domain=." + localHostAddr,273"CUSTOMER=WILE:BOB; PART_NUMBER=ROCKET_LAUNCHER_0001; SHIPPING=FEDEX",274"/foo"275)276};277278// check whether or not path rule is applied279testPolicies[count] = CookiePolicy.ACCEPT_ORIGINAL_SERVER;280testCases[count++] = new CookieTestCase[]{281new CookieTestCase("Set-Cookie",282"PART_NUMBER=ROCKET_LAUNCHER_0001; path=/;" + "domain=." + localHostAddr,283"PART_NUMBER=ROCKET_LAUNCHER_0001",284"/"285),286new CookieTestCase("Set-Cookie",287"PART_NUMBER=RIDING_ROCKET_0023; path=/ammo;" + "domain=." + localHostAddr,288"PART_NUMBER=RIDING_ROCKET_0023; PART_NUMBER=ROCKET_LAUNCHER_0001",289"/ammo"290)291};292293// an http session with rfc2965 cookies exchanged294testPolicies[count] = CookiePolicy.ACCEPT_ORIGINAL_SERVER;295testCases[count++] = new CookieTestCase[]{296new CookieTestCase("Set-Cookie2",297"Customer=\"WILE_E_COYOTE\"; Version=\"1\"; Path=\"/acme\";" + "domain=." + localHostAddr,298"$Version=\"1\"; Customer=\"WILE_E_COYOTE\";$Path=\"/acme\";$Domain=\"." + localHostAddr + "\"",299"/acme/login"300),301new CookieTestCase("Set-Cookie2",302"Part_Number=\"Rocket_Launcher_0001\"; Version=\"1\";Path=\"/acme\";" + "domain=." + localHostAddr,303"$Version=\"1\"; Customer=\"WILE_E_COYOTE\";$Path=\"/acme\";" + "$Domain=\"." +304localHostAddr + "\"" + "; Part_Number=\"Rocket_Launcher_0001\";$Path=\"/acme\";"305+ "$Domain=\"." + localHostAddr + "\"",306"/acme/pickitem"307),308new CookieTestCase("Set-Cookie2",309"Shipping=\"FedEx\"; Version=\"1\"; Path=\"/acme\";" + "domain=." + localHostAddr,310"$Version=\"1\"; Customer=\"WILE_E_COYOTE\";$Path=\"/acme\";" + "$Domain=\"." + localHostAddr +311"\"" + "; Part_Number=\"Rocket_Launcher_0001\";$Path=\"/acme\";" + "$Domain=\"."312+ localHostAddr + "\"" + "; Shipping=\"FedEx\";$Path=\"/acme\";" +313"$Domain=\"." + localHostAddr + "\"",314"/acme/shipping"315)316};317318// check whether or not the path rule is applied319testPolicies[count] = CookiePolicy.ACCEPT_ORIGINAL_SERVER;320testCases[count++] = new CookieTestCase[]{321new CookieTestCase("Set-Cookie2",322"Part_Number=\"Rocket_Launcher_0001\"; Version=\"1\"; Path=\"/acme\";" + "domain=." + localHostAddr,323"$Version=\"1\"; Part_Number=\"Rocket_Launcher_0001\";$Path=\"/acme\";$Domain=\"." + localHostAddr + "\"",324"/acme/ammo"325),326new CookieTestCase("Set-Cookie2",327"Part_Number=\"Riding_Rocket_0023\"; Version=\"1\"; Path=\"/acme/ammo\";" + "domain=."328+ localHostAddr,329"$Version=\"1\"; Part_Number=\"Riding_Rocket_0023\";$Path=\"/acme/ammo\";$Domain=\"."330+ localHostAddr + "\"" + "; Part_Number=\"Rocket_Launcher_0001\";$Path=\"/acme\";"331+ "$Domain=\"." + localHostAddr + "\"",332"/acme/ammo"333),334new CookieTestCase("",335"",336"$Version=\"1\"; Part_Number=\"Rocket_Launcher_0001\";$Path=\"/acme\";" + "$Domain=\"." + localHostAddr + "\"",337"/acme/parts"338)339};340341// new cookie should overwrite old cookie342testPolicies[count] = CookiePolicy.ACCEPT_ORIGINAL_SERVER;343testCases[count++] = new CookieTestCase[]{344new CookieTestCase("Set-Cookie2",345"Part_Number=\"Rocket_Launcher_0001\"; Version=\"1\"; Path=\"/acme\";" + "domain=." + localHostAddr,346"$Version=\"1\"; Part_Number=\"Rocket_Launcher_0001\";$Path=\"/acme\";$Domain=\"." + localHostAddr + "\"",347"/acme"348),349new CookieTestCase("Set-Cookie2",350"Part_Number=\"Rocket_Launcher_2000\"; Version=\"1\"; Path=\"/acme\";" + "domain=." + localHostAddr,351"$Version=\"1\"; Part_Number=\"Rocket_Launcher_2000\";$Path=\"/acme\";$Domain=\"." + localHostAddr + "\"",352"/acme"353)354};355356// cookies without domain attributes357// RFC 2965 states that domain should default to host358testPolicies[count] = CookiePolicy.ACCEPT_ALL;359testCases[count++] = new CookieTestCase[]{360new CookieTestCase("Set-Cookie2",361"Customer=\"WILE_E_COYOTE\"; Version=\"1\"; Path=\"/acme\"",362"$Version=\"1\"; Customer=\"WILE_E_COYOTE\";$Path=\"/acme\";$Domain=\""+localHostAddr+"\"",363"/acme/login"364),365new CookieTestCase("Set-Cookie2",366"Part_Number=\"Rocket_Launcher_0001\"; Version=\"1\";Path=\"/acme\"",367"$Version=\"1\"; Customer=\"WILE_E_COYOTE\";$Path=\"/acme\";$Domain=\""+localHostAddr+"\"" +368"; Part_Number=\"Rocket_Launcher_0001\";$Path=\"/acme\";$Domain=\""+localHostAddr+"\"",369"/acme/pickitem"370),371new CookieTestCase("Set-Cookie2",372"Shipping=\"FedEx\"; Version=\"1\"; Path=\"/acme\"",373"$Version=\"1\"; Customer=\"WILE_E_COYOTE\";$Path=\"/acme\";$Domain=\""+localHostAddr+"\"" +374"; Part_Number=\"Rocket_Launcher_0001\";$Path=\"/acme\";$Domain=\""+localHostAddr+"\"" +375"; Shipping=\"FedEx\";$Path=\"/acme\";$Domain=\""+localHostAddr+"\"",376"/acme/shipping"377)378};379380assert count == testCount;381}382}383384385