@Test public void testRedirectsDoNotIncludeTooManyCookies() throws Exception { MockWebServer redirectTarget = new MockWebServer(); redirectTarget.enqueue(new MockResponse().setBody("A")); redirectTarget.start(); MockWebServer redirectSource = new MockWebServer(); redirectSource.enqueue( new MockResponse() .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) .addHeader("Location: " + redirectTarget.url("/"))); redirectSource.start(); CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER); HttpCookie cookie = new HttpCookie("c", "cookie"); cookie.setDomain(redirectSource.getHostName()); cookie.setPath("/"); String portList = Integer.toString(redirectSource.getPort()); cookie.setPortlist(portList); cookieManager.getCookieStore().add(redirectSource.url("/").uri(), cookie); client.setCookieJar(new JavaNetCookieJar(cookieManager)); get(redirectSource.url("/")); RecordedRequest request = redirectSource.takeRequest(); assertEquals("c=cookie", request.getHeader("Cookie")); for (String header : redirectTarget.takeRequest().getHeaders().names()) { if (header.startsWith("Cookie")) { fail(header); } } }
/** * Sets cookies according to uri and responseHeaders * * @param uri the specified uri * @param responseHeaders a list of request headers * @throws IOException if some error of I/O operation occurs */ @Override public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException { if (uri == null || responseHeaders == null) { throw new IllegalArgumentException(); } // parse and construct cookies according to the map List<HttpCookie> cookies = parseCookie(responseHeaders); for (HttpCookie cookie : cookies) { // if the cookie doesn't have a domain, set one. The policy will do validation. if (cookie.getDomain() == null) { cookie.setDomain(uri.getHost()); } // if the cookie doesn't have a path, set one. If it does, validate it. if (cookie.getPath() == null) { cookie.setPath(pathToCookiePath(uri.getPath())); } else if (!HttpCookie.pathMatches(cookie, uri)) { continue; } // if the cookie has the placeholder port list "", set the port. Otherwise validate it. if ("".equals(cookie.getPortlist())) { cookie.setPortlist(Integer.toString(uri.getEffectivePort())); } else if (cookie.getPortlist() != null && !HttpCookie.portMatches(cookie, uri)) { continue; } // if the cookie conforms to the policy, add it into the store if (policy.shouldAccept(uri, cookie)) { store.add(uri, cookie); } } }
public HttpCookie toHttpCookie() { HttpCookie cookie = new HttpCookie(name, value); cookie.setComment(comment); cookie.setCommentURL(commentURL); cookie.setDiscard(discard); cookie.setDomain(domain); cookie.setMaxAge((expiry - System.currentTimeMillis()) / 1000L); cookie.setPath(path); cookie.setPortlist(portList); cookie.setSecure(secure); cookie.setVersion(version); return cookie; }
public static HttpCookie fromNewCookie(NewCookie c) { HttpCookie cookie = new HttpCookie(c.getName(), c.getValue()); cookie.setComment(c.getComment()); cookie.setCommentURL("not available"); cookie.setDiscard(false); cookie.setDomain(c.getDomain()); cookie.setMaxAge(c.getMaxAge()); cookie.setPath(c.getPath()); cookie.setPortlist("not available"); cookie.setSecure(c.isSecure()); cookie.setVersion(c.getVersion()); cookie.setHttpOnly(c.isHttpOnly()); return cookie; }
@Test public void testRedirectsDoNotIncludeTooManyCookies() throws Exception { MockWebServer redirectTarget = new MockWebServer(); redirectTarget.enqueue(new MockResponse().setBody("A")); redirectTarget.play(); MockWebServer redirectSource = new MockWebServer(); redirectSource.enqueue( new MockResponse() .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) .addHeader("Location: " + redirectTarget.getUrl("/"))); redirectSource.play(); CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER); HttpCookie cookie = new HttpCookie("c", "cookie"); cookie.setDomain(redirectSource.getCookieDomain()); cookie.setPath("/"); String portList = Integer.toString(redirectSource.getPort()); cookie.setPortlist(portList); cookieManager.getCookieStore().add(redirectSource.getUrl("/").toURI(), cookie); CookieHandler.setDefault(cookieManager); get(redirectSource, "/"); RecordedRequest request = redirectSource.takeRequest(); assertContains( request.getHeaders(), "Cookie: $Version=\"1\"; " + "c=\"cookie\";$Path=\"/\";$Domain=\"" + redirectSource.getCookieDomain() + "\";$Port=\"" + portList + "\""); for (String header : redirectTarget.takeRequest().getHeaders()) { if (header.startsWith("Cookie")) { fail(header); } } }
public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException { // pre-condition check if (uri == null || responseHeaders == null) { throw new IllegalArgumentException("Argument is null"); } // if there's no default CookieStore, no need to remember any cookie if (cookieJar == null) return; PlatformLogger logger = PlatformLogger.getLogger("java.net.CookieManager"); for (String headerKey : responseHeaders.keySet()) { // RFC 2965 3.2.2, key must be 'Set-Cookie2' // we also accept 'Set-Cookie' here for backward compatibility if (headerKey == null || !(headerKey.equalsIgnoreCase("Set-Cookie2") || headerKey.equalsIgnoreCase("Set-Cookie"))) { continue; } for (String headerValue : responseHeaders.get(headerKey)) { try { List<HttpCookie> cookies; try { cookies = HttpCookie.parse(headerValue); } catch (IllegalArgumentException e) { // Bogus header, make an empty list and log the error cookies = java.util.Collections.EMPTY_LIST; if (logger.isLoggable(PlatformLogger.SEVERE)) { logger.severe("Invalid cookie for " + uri + ": " + headerValue); } } for (HttpCookie cookie : cookies) { if (cookie.getPath() == null) { // If no path is specified, then by default // the path is the directory of the page/doc String path = uri.getPath(); if (!path.endsWith("/")) { int i = path.lastIndexOf("/"); if (i > 0) { path = path.substring(0, i + 1); } else { path = "/"; } } cookie.setPath(path); } // As per RFC 2965, section 3.3.1: // Domain Defaults to the effective request-host. (Note that because // there is no dot at the beginning of effective request-host, // the default Domain can only domain-match itself.) if (cookie.getDomain() == null) { cookie.setDomain(uri.getHost()); } String ports = cookie.getPortlist(); if (ports != null) { int port = uri.getPort(); if (port == -1) { port = "https".equals(uri.getScheme()) ? 443 : 80; } if (ports.isEmpty()) { // Empty port list means this should be restricted // to the incoming URI port cookie.setPortlist("" + port); if (shouldAcceptInternal(uri, cookie)) { cookieJar.add(uri, cookie); } } else { // Only store cookies with a port list // IF the URI port is in that list, as per // RFC 2965 section 3.3.2 if (isInPortList(ports, port) && shouldAcceptInternal(uri, cookie)) { cookieJar.add(uri, cookie); } } } else { if (shouldAcceptInternal(uri, cookie)) { cookieJar.add(uri, cookie); } } } } catch (IllegalArgumentException e) { // invalid set-cookie header string // no-op } } } }