You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

NetscapeCookieFileTest.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /*
  2. * Copyright (C) 2018, Konrad Windszus <konrad_w@gmx.de>
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.internal.transport.http;
  44. import java.io.IOException;
  45. import java.io.InputStream;
  46. import java.io.Writer;
  47. import java.net.HttpCookie;
  48. import java.net.URL;
  49. import java.nio.charset.StandardCharsets;
  50. import java.nio.file.Files;
  51. import java.nio.file.Path;
  52. import java.nio.file.StandardCopyOption;
  53. import java.time.Instant;
  54. import java.util.Arrays;
  55. import java.util.Date;
  56. import java.util.LinkedHashSet;
  57. import java.util.List;
  58. import java.util.Set;
  59. import java.util.regex.Pattern;
  60. import org.eclipse.jgit.internal.storage.file.LockFile;
  61. import org.eclipse.jgit.util.http.HttpCookiesMatcher;
  62. import org.hamcrest.CoreMatchers;
  63. import org.junit.Assert;
  64. import org.junit.Before;
  65. import org.junit.Rule;
  66. import org.junit.Test;
  67. import org.junit.rules.TemporaryFolder;
  68. public class NetscapeCookieFileTest {
  69. @Rule
  70. public TemporaryFolder folder = new TemporaryFolder();
  71. private Path tmpFile;
  72. private URL baseUrl;
  73. /**
  74. * This is the expiration date that is used in the test cookie files
  75. */
  76. private static long JAN_01_2030_NOON = Instant
  77. .parse("2030-01-01T12:00:00.000Z").toEpochMilli();
  78. @Before
  79. public void setUp() throws IOException {
  80. // this will not only return a new file name but also create new empty
  81. // file!
  82. tmpFile = folder.newFile().toPath();
  83. baseUrl = new URL("http://domain.com/my/path");
  84. }
  85. @Test
  86. public void testMergeCookies() {
  87. Set<HttpCookie> cookieSet1 = new LinkedHashSet<>();
  88. HttpCookie cookie = new HttpCookie("key1", "valueFromSet1");
  89. cookieSet1.add(cookie);
  90. cookie = new HttpCookie("key2", "valueFromSet1");
  91. cookieSet1.add(cookie);
  92. Set<HttpCookie> cookieSet2 = new LinkedHashSet<>();
  93. cookie = new HttpCookie("key1", "valueFromSet2");
  94. cookieSet2.add(cookie);
  95. cookie = new HttpCookie("key3", "valueFromSet2");
  96. cookieSet2.add(cookie);
  97. Set<HttpCookie> cookiesExpectedMergedSet = new LinkedHashSet<>();
  98. cookie = new HttpCookie("key1", "valueFromSet1");
  99. cookiesExpectedMergedSet.add(cookie);
  100. cookie = new HttpCookie("key2", "valueFromSet1");
  101. cookiesExpectedMergedSet.add(cookie);
  102. cookie = new HttpCookie("key3", "valueFromSet2");
  103. cookiesExpectedMergedSet.add(cookie);
  104. Assert.assertThat(
  105. NetscapeCookieFile.mergeCookies(cookieSet1, cookieSet2),
  106. HttpCookiesMatcher.containsInOrder(cookiesExpectedMergedSet));
  107. Assert.assertThat(NetscapeCookieFile.mergeCookies(cookieSet1, null),
  108. HttpCookiesMatcher.containsInOrder(cookieSet1));
  109. }
  110. @Test
  111. public void testWriteToNewFile() throws IOException {
  112. Set<HttpCookie> cookies = new LinkedHashSet<>();
  113. cookies.add(new HttpCookie("key1", "value"));
  114. // first cookie is a session cookie (and should be ignored)
  115. HttpCookie cookie = new HttpCookie("key2", "value");
  116. cookie.setSecure(true);
  117. cookie.setDomain("mydomain.com");
  118. cookie.setPath("/");
  119. cookie.setMaxAge(1000);
  120. cookies.add(cookie);
  121. Date creationDate = new Date();
  122. try (Writer writer = Files.newBufferedWriter(tmpFile,
  123. StandardCharsets.US_ASCII)) {
  124. NetscapeCookieFile.write(writer, cookies, baseUrl, creationDate);
  125. }
  126. String expectedExpiration = String
  127. .valueOf(creationDate.getTime() + (cookie.getMaxAge() * 1000));
  128. Assert.assertThat(
  129. Files.readAllLines(tmpFile, StandardCharsets.US_ASCII),
  130. CoreMatchers
  131. .equalTo(Arrays.asList("mydomain.com\tTRUE\t/\tTRUE\t"
  132. + expectedExpiration + "\tkey2\tvalue")));
  133. }
  134. @Test
  135. public void testWriteToExistingFile() throws IOException {
  136. try (InputStream input = this.getClass()
  137. .getResourceAsStream("cookies-simple1.txt")) {
  138. Files.copy(input, tmpFile, StandardCopyOption.REPLACE_EXISTING);
  139. }
  140. Set<HttpCookie> cookies = new LinkedHashSet<>();
  141. HttpCookie cookie = new HttpCookie("key2", "value2");
  142. cookie.setMaxAge(1000);
  143. cookies.add(cookie);
  144. Date creationDate = new Date();
  145. try (Writer writer = Files.newBufferedWriter(tmpFile,
  146. StandardCharsets.US_ASCII)) {
  147. NetscapeCookieFile.write(writer, cookies, baseUrl, creationDate);
  148. }
  149. String expectedExpiration = String
  150. .valueOf(creationDate.getTime() + (cookie.getMaxAge() * 1000));
  151. Assert.assertThat(
  152. Files.readAllLines(tmpFile, StandardCharsets.US_ASCII),
  153. CoreMatchers.equalTo(
  154. Arrays.asList("domain.com\tTRUE\t/my/path\tFALSE\t"
  155. + expectedExpiration + "\tkey2\tvalue2")));
  156. }
  157. @Test(expected = IOException.class)
  158. public void testWriteWhileSomeoneIsHoldingTheLock()
  159. throws IllegalArgumentException, IOException, InterruptedException {
  160. try (InputStream input = this.getClass()
  161. .getResourceAsStream("cookies-simple1.txt")) {
  162. Files.copy(input, tmpFile, StandardCopyOption.REPLACE_EXISTING);
  163. }
  164. NetscapeCookieFile cookieFile = new NetscapeCookieFile(tmpFile);
  165. // now imitate another process/thread holding the lock file
  166. LockFile lockFile = new LockFile(tmpFile.toFile());
  167. try {
  168. Assert.assertTrue("Could not acquire lock", lockFile.lock());
  169. cookieFile.write(baseUrl);
  170. } finally {
  171. lockFile.unlock();
  172. }
  173. }
  174. @Test
  175. public void testWriteAfterAnotherJgitProcessModifiedTheFile()
  176. throws IOException, InterruptedException {
  177. try (InputStream input = this.getClass()
  178. .getResourceAsStream("cookies-simple1.txt")) {
  179. Files.copy(input, tmpFile, StandardCopyOption.REPLACE_EXISTING);
  180. }
  181. NetscapeCookieFile cookieFile = new NetscapeCookieFile(tmpFile);
  182. cookieFile.getCookies(true);
  183. // now modify file externally
  184. try (InputStream input = this.getClass()
  185. .getResourceAsStream("cookies-simple2.txt")) {
  186. Files.copy(input, tmpFile, StandardCopyOption.REPLACE_EXISTING);
  187. }
  188. // now try to write
  189. cookieFile.write(baseUrl);
  190. // validate that the external changes are there as well
  191. // due to rounding errors (conversion from ms to sec to ms)
  192. // the expiration date might not be exact
  193. List<String> lines = Files.readAllLines(tmpFile,
  194. StandardCharsets.US_ASCII);
  195. Assert.assertEquals("Expected 3 lines", 3, lines.size());
  196. assertStringMatchesPatternWithInexactNumber(lines.get(0),
  197. "some-domain1\tTRUE\t/some/path1\tFALSE\t(\\d*)\tkey1\tvalueFromSimple2",
  198. JAN_01_2030_NOON, 1000);
  199. assertStringMatchesPatternWithInexactNumber(lines.get(1),
  200. "some-domain1\tTRUE\t/some/path1\tFALSE\t(\\d*)\tkey3\tvalueFromSimple2",
  201. JAN_01_2030_NOON, 1000);
  202. assertStringMatchesPatternWithInexactNumber(lines.get(2),
  203. "some-domain1\tTRUE\t/some/path1\tFALSE\t(\\d*)\tkey2\tvalueFromSimple1",
  204. JAN_01_2030_NOON, 1000);
  205. }
  206. @SuppressWarnings("boxing")
  207. private static final void assertStringMatchesPatternWithInexactNumber(
  208. String string, String pattern, long expectedNumericValue,
  209. long delta) {
  210. java.util.regex.Matcher matcher = Pattern.compile(pattern)
  211. .matcher(string);
  212. Assert.assertTrue("Given string '" + string + "' does not match '"
  213. + pattern + "'", matcher.matches());
  214. // extract numeric value
  215. Long actualNumericValue = Long.decode(matcher.group(1));
  216. Assert.assertTrue(
  217. "Value is supposed to be close to " + expectedNumericValue
  218. + " but is " + actualNumericValue + ".",
  219. Math.abs(expectedNumericValue - actualNumericValue) <= delta);
  220. }
  221. @Test
  222. public void testWriteAndReadCycle() throws IOException {
  223. Set<HttpCookie> cookies = new LinkedHashSet<>();
  224. HttpCookie cookie = new HttpCookie("key1", "value1");
  225. cookie.setPath("/some/path1");
  226. cookie.setDomain("some-domain1");
  227. cookie.setMaxAge(1000);
  228. cookies.add(cookie);
  229. cookie = new HttpCookie("key2", "value2");
  230. cookie.setSecure(true);
  231. cookie.setPath("/some/path2");
  232. cookie.setDomain("some-domain2");
  233. cookie.setMaxAge(1000);
  234. cookie.setHttpOnly(true);
  235. cookies.add(cookie);
  236. Date creationDate = new Date();
  237. try (Writer writer = Files.newBufferedWriter(tmpFile,
  238. StandardCharsets.US_ASCII)) {
  239. NetscapeCookieFile.write(writer, cookies, baseUrl, creationDate);
  240. }
  241. Set<HttpCookie> actualCookies = new NetscapeCookieFile(tmpFile,
  242. creationDate).getCookies(true);
  243. Assert.assertThat(actualCookies,
  244. HttpCookiesMatcher.containsInOrder(cookies));
  245. }
  246. @Test
  247. public void testReadAndWriteCycle() throws IOException {
  248. try (InputStream input = this.getClass()
  249. .getResourceAsStream("cookies-simple1.txt")) {
  250. Files.copy(input, tmpFile, StandardCopyOption.REPLACE_EXISTING);
  251. }
  252. // round up to the next second (to prevent rounding errors)
  253. Date creationDate = new Date(
  254. (System.currentTimeMillis() / 1000) * 1000);
  255. Set<HttpCookie> cookies = new NetscapeCookieFile(tmpFile, creationDate)
  256. .getCookies(true);
  257. Path tmpFile2 = folder.newFile().toPath();
  258. try (Writer writer = Files.newBufferedWriter(tmpFile2,
  259. StandardCharsets.US_ASCII)) {
  260. NetscapeCookieFile.write(writer, cookies, baseUrl, creationDate);
  261. }
  262. // compare original file with newly written one, they should not differ
  263. Assert.assertEquals(Files.readAllLines(tmpFile),
  264. Files.readAllLines(tmpFile2));
  265. }
  266. @Test
  267. public void testReadWithEmptyAndCommentLines() throws IOException {
  268. try (InputStream input = this.getClass().getResourceAsStream(
  269. "cookies-with-empty-and-comment-lines.txt")) {
  270. Files.copy(input, tmpFile, StandardCopyOption.REPLACE_EXISTING);
  271. }
  272. Date creationDate = new Date();
  273. Set<HttpCookie> cookies = new LinkedHashSet<>();
  274. HttpCookie cookie = new HttpCookie("key2", "value2");
  275. cookie.setDomain("some-domain2");
  276. cookie.setPath("/some/path2");
  277. cookie.setMaxAge((JAN_01_2030_NOON - creationDate.getTime()) / 1000);
  278. cookie.setSecure(true);
  279. cookie.setHttpOnly(true);
  280. cookies.add(cookie);
  281. cookie = new HttpCookie("key3", "value3");
  282. cookie.setDomain("some-domain3");
  283. cookie.setPath("/some/path3");
  284. cookie.setMaxAge((JAN_01_2030_NOON - creationDate.getTime()) / 1000);
  285. cookies.add(cookie);
  286. Set<HttpCookie> actualCookies = new NetscapeCookieFile(tmpFile, creationDate)
  287. .getCookies(true);
  288. Assert.assertThat(actualCookies,
  289. HttpCookiesMatcher.containsInOrder(cookies));
  290. }
  291. @Test
  292. public void testReadInvalidFile() throws IOException {
  293. try (InputStream input = this.getClass()
  294. .getResourceAsStream("cookies-invalid.txt")) {
  295. Files.copy(input, tmpFile, StandardCopyOption.REPLACE_EXISTING);
  296. }
  297. new NetscapeCookieFile(tmpFile)
  298. .getCookies(true);
  299. }
  300. }