Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

WalkEncryptionTest.java 36KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  1. /*
  2. * Copyright (C) 2015, Andrei Pozolotin. and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.transport;
  11. import static java.nio.charset.StandardCharsets.UTF_8;
  12. import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.cryptoCipherListPBE;
  13. import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.cryptoCipherListTrans;
  14. import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.folderDelete;
  15. import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.permitLongTests;
  16. import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.policySetup;
  17. import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.product;
  18. import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.proxySetup;
  19. import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.publicAddress;
  20. import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.reportPolicy;
  21. import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.securityProviderName;
  22. import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.textWrite;
  23. import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.transferStream;
  24. import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.verifyFileContent;
  25. import static org.junit.Assert.assertEquals;
  26. import static org.junit.Assert.assertFalse;
  27. import static org.junit.Assert.assertNotNull;
  28. import static org.junit.Assert.assertTrue;
  29. import static org.junit.Assume.assumeTrue;
  30. import java.io.BufferedReader;
  31. import java.io.ByteArrayInputStream;
  32. import java.io.ByteArrayOutputStream;
  33. import java.io.File;
  34. import java.io.FileInputStream;
  35. import java.io.IOException;
  36. import java.io.InputStream;
  37. import java.io.InputStreamReader;
  38. import java.io.OutputStream;
  39. import java.io.PrintWriter;
  40. import java.net.SocketTimeoutException;
  41. import java.net.URL;
  42. import java.net.URLConnection;
  43. import java.net.UnknownHostException;
  44. import java.nio.file.Files;
  45. import java.security.GeneralSecurityException;
  46. import java.security.Provider;
  47. import java.security.Security;
  48. import java.util.ArrayList;
  49. import java.util.Collection;
  50. import java.util.List;
  51. import java.util.Locale;
  52. import java.util.Properties;
  53. import java.util.Set;
  54. import java.util.TreeSet;
  55. import java.util.UUID;
  56. import javax.crypto.SecretKeyFactory;
  57. import org.eclipse.jgit.api.Git;
  58. import org.eclipse.jgit.lib.StoredConfig;
  59. import org.eclipse.jgit.test.resources.SampleDataRepositoryTestCase;
  60. import org.eclipse.jgit.util.FileUtils;
  61. import org.junit.After;
  62. import org.junit.AfterClass;
  63. import org.junit.Before;
  64. import org.junit.BeforeClass;
  65. import org.junit.FixMethodOrder;
  66. import org.junit.Test;
  67. import org.junit.runner.RunWith;
  68. import org.junit.runners.MethodSorters;
  69. import org.junit.runners.Parameterized;
  70. import org.junit.runners.Parameterized.Parameters;
  71. import org.junit.runners.Suite;
  72. import org.slf4j.Logger;
  73. import org.slf4j.LoggerFactory;
  74. /**
  75. * Amazon S3 encryption pipeline test.
  76. *
  77. * See {@link AmazonS3} {@link WalkEncryption}
  78. *
  79. * Note: CI server must provide amazon credentials (access key, secret key,
  80. * bucket name) via one of methods available in {@link Names}.
  81. *
  82. * Note: long running tests are activated by Maven profile "test.long". There is
  83. * also a separate Eclipse m2e launcher for that. See 'pom.xml' and
  84. * 'WalkEncryptionTest.launch'.
  85. */
  86. @RunWith(Suite.class)
  87. @Suite.SuiteClasses({ //
  88. WalkEncryptionTest.Required.class, //
  89. WalkEncryptionTest.MinimalSet.class, //
  90. WalkEncryptionTest.TestablePBE.class, //
  91. WalkEncryptionTest.TestableTransformation.class, //
  92. })
  93. public class WalkEncryptionTest {
  94. /**
  95. * Logger setup: ${project_loc}/tst-rsrc/log4j.properties
  96. */
  97. static final Logger logger = LoggerFactory.getLogger(WalkEncryptionTest.class);
  98. /**
  99. * Property names used in test session.
  100. */
  101. interface Names {
  102. // Names of discovered test properties.
  103. String TEST_BUCKET = "test.bucket";
  104. // Names of test environment variables for CI.
  105. String ENV_ACCESS_KEY = "JGIT_S3_ACCESS_KEY";
  106. String ENV_SECRET_KEY = "JGIT_S3_SECRET_KEY";
  107. String ENV_BUCKET_NAME = "JGIT_S3_BUCKET_NAME";
  108. // Name of test environment variable file path for CI.
  109. String ENV_CONFIG_FILE = "JGIT_S3_CONFIG_FILE";
  110. // Names of test system properties for CI.
  111. String SYS_ACCESS_KEY = "jgit.s3.access.key";
  112. String SYS_SECRET_KEY = "jgit.s3.secret.key";
  113. String SYS_BUCKET_NAME = "jgit.s3.bucket.name";
  114. // Name of test system property file path for CI.
  115. String SYS_CONFIG_FILE = "jgit.s3.config.file";
  116. // Hard coded name of test properties file for CI.
  117. // File format follows AmazonS3.Keys:
  118. // #
  119. // # Required entries:
  120. // #
  121. // accesskey = your-amazon-access-key # default AmazonS3.Keys
  122. // secretkey = your-amazon-secret-key # default AmazonS3.Keys
  123. // test.bucket = your-bucket-for-testing # custom name, for this test
  124. String CONFIG_FILE = "jgit-s3-config.properties";
  125. // Test properties file in [user home] of CI.
  126. String HOME_CONFIG_FILE = System.getProperty("user.home")
  127. + File.separator + CONFIG_FILE;
  128. // Test properties file in [project work directory] of CI.
  129. String WORK_CONFIG_FILE = System.getProperty("user.dir")
  130. + File.separator + CONFIG_FILE;
  131. // Test properties file in [project test source directory] of CI.
  132. String TEST_CONFIG_FILE = System.getProperty("user.dir")
  133. + File.separator + "tst-rsrc" + File.separator + CONFIG_FILE;
  134. }
  135. /**
  136. * Find test properties from various sources in order of priority.
  137. */
  138. static class Props implements WalkEncryptionTest.Names, AmazonS3.Keys {
  139. static boolean haveEnvVar(String name) {
  140. return System.getenv(name) != null;
  141. }
  142. static boolean haveEnvVarFile(String name) {
  143. return haveEnvVar(name) && new File(name).exists();
  144. }
  145. static boolean haveSysProp(String name) {
  146. return System.getProperty(name) != null;
  147. }
  148. static boolean haveSysPropFile(String name) {
  149. return haveSysProp(name) && new File(name).exists();
  150. }
  151. static void loadEnvVar(String source, String target, Properties props) {
  152. props.put(target, System.getenv(source));
  153. }
  154. static void loadSysProp(String source, String target,
  155. Properties props) {
  156. props.put(target, System.getProperty(source));
  157. }
  158. static boolean haveProp(String name, Properties props) {
  159. return props.containsKey(name);
  160. }
  161. static boolean checkTestProps(Properties props) {
  162. return haveProp(ACCESS_KEY, props) && haveProp(SECRET_KEY, props)
  163. && haveProp(TEST_BUCKET, props);
  164. }
  165. static Properties fromEnvVars() {
  166. if (haveEnvVar(ENV_ACCESS_KEY) && haveEnvVar(ENV_SECRET_KEY)
  167. && haveEnvVar(ENV_BUCKET_NAME)) {
  168. Properties props = new Properties();
  169. loadEnvVar(ENV_ACCESS_KEY, ACCESS_KEY, props);
  170. loadEnvVar(ENV_SECRET_KEY, SECRET_KEY, props);
  171. loadEnvVar(ENV_BUCKET_NAME, TEST_BUCKET, props);
  172. return props;
  173. }
  174. return null;
  175. }
  176. static Properties fromEnvFile() throws Exception {
  177. if (haveEnvVarFile(ENV_CONFIG_FILE)) {
  178. Properties props = new Properties();
  179. props.load(new FileInputStream(ENV_CONFIG_FILE));
  180. if (checkTestProps(props)) {
  181. return props;
  182. }
  183. throw new Error("Environment config file is incomplete.");
  184. }
  185. return null;
  186. }
  187. static Properties fromSysProps() {
  188. if (haveSysProp(SYS_ACCESS_KEY) && haveSysProp(SYS_SECRET_KEY)
  189. && haveSysProp(SYS_BUCKET_NAME)) {
  190. Properties props = new Properties();
  191. loadSysProp(SYS_ACCESS_KEY, ACCESS_KEY, props);
  192. loadSysProp(SYS_SECRET_KEY, SECRET_KEY, props);
  193. loadSysProp(SYS_BUCKET_NAME, TEST_BUCKET, props);
  194. return props;
  195. }
  196. return null;
  197. }
  198. static Properties fromSysFile() throws Exception {
  199. if (haveSysPropFile(SYS_CONFIG_FILE)) {
  200. Properties props = new Properties();
  201. props.load(new FileInputStream(SYS_CONFIG_FILE));
  202. if (checkTestProps(props)) {
  203. return props;
  204. }
  205. throw new Error("System props config file is incomplete.");
  206. }
  207. return null;
  208. }
  209. static Properties fromConfigFile(String path) throws Exception {
  210. File file = new File(path);
  211. if (file.exists()) {
  212. Properties props = new Properties();
  213. props.load(new FileInputStream(file));
  214. if (checkTestProps(props)) {
  215. return props;
  216. }
  217. throw new Error("Props config file is incomplete: " + path);
  218. }
  219. return null;
  220. }
  221. /**
  222. * Find test properties from various sources in order of priority.
  223. *
  224. * @return result
  225. * @throws Exception
  226. */
  227. static Properties discover() throws Exception {
  228. Properties props;
  229. if ((props = fromEnvVars()) != null) {
  230. logger.debug(
  231. "Using test properties from environment variables.");
  232. return props;
  233. }
  234. if ((props = fromEnvFile()) != null) {
  235. logger.debug(
  236. "Using test properties from environment variable config file.");
  237. return props;
  238. }
  239. if ((props = fromSysProps()) != null) {
  240. logger.debug("Using test properties from system properties.");
  241. return props;
  242. }
  243. if ((props = fromSysFile()) != null) {
  244. logger.debug(
  245. "Using test properties from system property config file.");
  246. return props;
  247. }
  248. if ((props = fromConfigFile(HOME_CONFIG_FILE)) != null) {
  249. logger.debug(
  250. "Using test properties from hard coded ${user.home} file.");
  251. return props;
  252. }
  253. if ((props = fromConfigFile(WORK_CONFIG_FILE)) != null) {
  254. logger.debug(
  255. "Using test properties from hard coded ${user.dir} file.");
  256. return props;
  257. }
  258. if ((props = fromConfigFile(TEST_CONFIG_FILE)) != null) {
  259. logger.debug(
  260. "Using test properties from hard coded ${project.source} file.");
  261. return props;
  262. }
  263. throw new Error("Can not load test properties form any source.");
  264. }
  265. }
  266. /**
  267. * Collection of test utility methods.
  268. */
  269. static class Util {
  270. /**
  271. * Read UTF-8 encoded text file into string.
  272. *
  273. * @param file
  274. * @return result
  275. * @throws Exception
  276. */
  277. static String textRead(File file) throws Exception {
  278. return new String(Files.readAllBytes(file.toPath()), UTF_8);
  279. }
  280. /**
  281. * Write string into UTF-8 encoded file.
  282. *
  283. * @param file
  284. * @param text
  285. * @throws Exception
  286. */
  287. static void textWrite(File file, String text) throws Exception {
  288. Files.write(file.toPath(), text.getBytes(UTF_8));
  289. }
  290. static void verifyFileContent(File fileOne, File fileTwo)
  291. throws Exception {
  292. assertTrue(fileOne.length() > 0);
  293. assertTrue(fileTwo.length() > 0);
  294. String textOne = textRead(fileOne);
  295. String textTwo = textRead(fileTwo);
  296. assertEquals(textOne, textTwo);
  297. }
  298. /**
  299. * Create local folder.
  300. *
  301. * @param folder
  302. * @throws Exception
  303. */
  304. static void folderCreate(String folder) throws Exception {
  305. File path = new File(folder);
  306. assertTrue(path.mkdirs());
  307. }
  308. /**
  309. * Delete local folder.
  310. *
  311. * @param folder
  312. * @throws Exception
  313. */
  314. static void folderDelete(String folder) throws Exception {
  315. File path = new File(folder);
  316. FileUtils.delete(path,
  317. FileUtils.RECURSIVE | FileUtils.SKIP_MISSING);
  318. }
  319. /**
  320. * Discover public address of CI server.
  321. *
  322. * @return result
  323. * @throws Exception
  324. */
  325. static String publicAddress() throws Exception {
  326. try {
  327. String service = "http://checkip.amazonaws.com";
  328. URL url = new URL(service);
  329. URLConnection c = url.openConnection();
  330. c.setConnectTimeout(500);
  331. c.setReadTimeout(500);
  332. try (BufferedReader reader = new BufferedReader(
  333. new InputStreamReader(c.getInputStream(), UTF_8))) {
  334. return reader.readLine();
  335. }
  336. } catch (UnknownHostException | SocketTimeoutException e) {
  337. return "Can't reach http://checkip.amazonaws.com to"
  338. + " determine public address";
  339. }
  340. }
  341. /**
  342. * Discover Password-Based Encryption (PBE) engines providing both
  343. * [SecretKeyFactory] and [AlgorithmParameters].
  344. *
  345. * @return result
  346. */
  347. // https://www.bouncycastle.org/specifications.html
  348. // https://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html
  349. static List<String> cryptoCipherListPBE() {
  350. return cryptoCipherList(WalkEncryption.Vals.REGEX_PBE);
  351. }
  352. // TODO returns inconsistent list.
  353. static List<String> cryptoCipherListTrans() {
  354. return cryptoCipherList(WalkEncryption.Vals.REGEX_TRANS);
  355. }
  356. static String securityProviderName(String algorithm) throws Exception {
  357. return SecretKeyFactory.getInstance(algorithm).getProvider()
  358. .getName();
  359. }
  360. static List<String> cryptoCipherList(String regex) {
  361. Set<String> source = Security.getAlgorithms("Cipher");
  362. Set<String> target = new TreeSet<>();
  363. for (String algo : source) {
  364. algo = algo.toUpperCase(Locale.ROOT);
  365. if (algo.matches(regex)) {
  366. target.add(algo);
  367. }
  368. }
  369. return new ArrayList<>(target);
  370. }
  371. /**
  372. * Stream copy.
  373. *
  374. * @param from
  375. * @param into
  376. * @return count
  377. * @throws IOException
  378. */
  379. static long transferStream(InputStream from, OutputStream into)
  380. throws IOException {
  381. byte[] array = new byte[1 * 1024];
  382. long total = 0;
  383. while (true) {
  384. int count = from.read(array);
  385. if (count == -1) {
  386. break;
  387. }
  388. into.write(array, 0, count);
  389. total += count;
  390. }
  391. return total;
  392. }
  393. /**
  394. * Setup proxy during CI build.
  395. *
  396. * @throws Exception
  397. */
  398. // https://wiki.eclipse.org/Hudson#Accessing_the_Internet_using_Proxy
  399. // http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html
  400. static void proxySetup() throws Exception {
  401. String keyNoProxy = "no_proxy";
  402. String keyHttpProxy = "http_proxy";
  403. String keyHttpsProxy = "https_proxy";
  404. String no_proxy = System.getProperty(keyNoProxy,
  405. System.getenv(keyNoProxy));
  406. if (no_proxy != null) {
  407. System.setProperty("http.nonProxyHosts", no_proxy);
  408. logger.info("Proxy NOT: " + no_proxy);
  409. }
  410. String http_proxy = System.getProperty(keyHttpProxy,
  411. System.getenv(keyHttpProxy));
  412. if (http_proxy != null) {
  413. URL url = new URL(http_proxy);
  414. System.setProperty("http.proxyHost", url.getHost());
  415. System.setProperty("http.proxyPort", "" + url.getPort());
  416. logger.info("Proxy HTTP: " + http_proxy);
  417. }
  418. String https_proxy = System.getProperty(keyHttpsProxy,
  419. System.getenv(keyHttpsProxy));
  420. if (https_proxy != null) {
  421. URL url = new URL(https_proxy);
  422. System.setProperty("https.proxyHost", url.getHost());
  423. System.setProperty("https.proxyPort", "" + url.getPort());
  424. logger.info("Proxy HTTPS: " + https_proxy);
  425. }
  426. if (no_proxy == null && http_proxy == null && https_proxy == null) {
  427. logger.info("Proxy not used.");
  428. }
  429. }
  430. /**
  431. * Permit long tests on CI or with manual activation.
  432. *
  433. * @return result
  434. */
  435. static boolean permitLongTests() {
  436. return isBuildCI() || isProfileActive();
  437. }
  438. /**
  439. * Using Maven profile activation, see pom.xml
  440. *
  441. * @return result
  442. */
  443. static boolean isProfileActive() {
  444. return Boolean.parseBoolean(System.getProperty("jgit.test.long"));
  445. }
  446. /**
  447. * Detect if build is running on CI.
  448. *
  449. * @return result
  450. */
  451. static boolean isBuildCI() {
  452. return System.getenv("HUDSON_HOME") != null;
  453. }
  454. /**
  455. * Setup JCE security policy restrictions. Can remove restrictions when
  456. * restrictions are present, but can not impose them when restrictions
  457. * are missing.
  458. *
  459. * @param restrictedOn
  460. */
  461. // http://www.docjar.com/html/api/javax/crypto/JceSecurity.java.html
  462. static void policySetup(boolean restrictedOn) {
  463. try {
  464. java.lang.reflect.Field isRestricted = Class
  465. .forName("javax.crypto.JceSecurity")
  466. .getDeclaredField("isRestricted");
  467. isRestricted.setAccessible(true);
  468. isRestricted.set(null, Boolean.valueOf(restrictedOn));
  469. } catch (Throwable e) {
  470. logger.info(
  471. "Could not setup JCE security policy restrictions.");
  472. }
  473. }
  474. static void reportPolicy() {
  475. try {
  476. java.lang.reflect.Field isRestricted = Class
  477. .forName("javax.crypto.JceSecurity")
  478. .getDeclaredField("isRestricted");
  479. isRestricted.setAccessible(true);
  480. logger.info("JCE security policy restricted="
  481. + isRestricted.get(null));
  482. } catch (Throwable e) {
  483. logger.info(
  484. "Could not report JCE security policy restrictions.");
  485. }
  486. }
  487. static List<Object[]> product(List<String> one, List<String> two) {
  488. List<Object[]> result = new ArrayList<>();
  489. for (String s1 : one) {
  490. for (String s2 : two) {
  491. result.add(new Object[] { s1, s2 });
  492. }
  493. }
  494. return result;
  495. }
  496. }
  497. /**
  498. * Common base for encryption tests.
  499. */
  500. @FixMethodOrder(MethodSorters.NAME_ASCENDING)
  501. public abstract static class Base extends SampleDataRepositoryTestCase {
  502. /**
  503. * S3 URI user used by JGIT to discover connection configuration file.
  504. */
  505. static final String JGIT_USER = "tester-" + System.currentTimeMillis();
  506. /**
  507. * S3 content encoding password used for this test session.
  508. */
  509. static final String JGIT_PASS = "secret-" + System.currentTimeMillis();
  510. /**
  511. * S3 repository configuration file expected by {@link AmazonS3}.
  512. */
  513. static final String JGIT_CONF_FILE = System.getProperty("user.home")
  514. + "/" + JGIT_USER;
  515. /**
  516. * Name representing remote or local JGIT repository.
  517. */
  518. static final String JGIT_REPO_DIR = JGIT_USER + ".jgit";
  519. /**
  520. * Local JGIT repository for this test session.
  521. */
  522. static final String JGIT_LOCAL_DIR = System.getProperty("user.dir")
  523. + "/target/" + JGIT_REPO_DIR;
  524. /**
  525. * Remote JGIT repository for this test session.
  526. */
  527. static final String JGIT_REMOTE_DIR = JGIT_REPO_DIR;
  528. /**
  529. * Generate JGIT S3 connection configuration file.
  530. *
  531. * @param algorithm
  532. * @throws Exception
  533. */
  534. static void configCreate(String algorithm) throws Exception {
  535. Properties props = Props.discover();
  536. props.put(AmazonS3.Keys.PASSWORD, JGIT_PASS);
  537. props.put(AmazonS3.Keys.CRYPTO_ALG, algorithm);
  538. try (PrintWriter writer = new PrintWriter(JGIT_CONF_FILE,
  539. UTF_8.name())) {
  540. props.store(writer, "JGIT S3 connection configuration file.");
  541. }
  542. }
  543. /**
  544. * Generate JGIT S3 connection configuration file.
  545. *
  546. * @param source
  547. * @throws Exception
  548. */
  549. static void configCreate(Properties source) throws Exception {
  550. Properties target = Props.discover();
  551. target.putAll(source);
  552. try (PrintWriter writer = new PrintWriter(JGIT_CONF_FILE,
  553. UTF_8.name())) {
  554. target.store(writer, "JGIT S3 connection configuration file.");
  555. }
  556. }
  557. /**
  558. * Remove JGIT connection configuration file.
  559. *
  560. * @throws Exception
  561. */
  562. static void configDelete() throws Exception {
  563. File path = new File(JGIT_CONF_FILE);
  564. FileUtils.delete(path, FileUtils.SKIP_MISSING);
  565. }
  566. /**
  567. * Generate remote URI for the test session.
  568. *
  569. * @return result
  570. * @throws Exception
  571. */
  572. static String amazonURI() throws Exception {
  573. Properties props = Props.discover();
  574. String bucket = props.getProperty(Names.TEST_BUCKET);
  575. assertNotNull(bucket);
  576. return TransportAmazonS3.S3_SCHEME + "://" + JGIT_USER + "@"
  577. + bucket + "/" + JGIT_REPO_DIR;
  578. }
  579. /**
  580. * Create S3 repository folder.
  581. *
  582. * @throws Exception
  583. */
  584. static void remoteCreate() throws Exception {
  585. Properties props = Props.discover();
  586. props.remove(AmazonS3.Keys.PASSWORD); // Disable encryption.
  587. String bucket = props.getProperty(Names.TEST_BUCKET);
  588. AmazonS3 s3 = new AmazonS3(props);
  589. String path = JGIT_REMOTE_DIR + "/";
  590. s3.put(bucket, path, new byte[0]);
  591. logger.debug("remote create: " + JGIT_REMOTE_DIR);
  592. }
  593. /**
  594. * Delete S3 repository folder.
  595. *
  596. * @throws Exception
  597. */
  598. static void remoteDelete() throws Exception {
  599. Properties props = Props.discover();
  600. props.remove(AmazonS3.Keys.PASSWORD); // Disable encryption.
  601. String bucket = props.getProperty(Names.TEST_BUCKET);
  602. AmazonS3 s3 = new AmazonS3(props);
  603. List<String> list = s3.list(bucket, JGIT_REMOTE_DIR);
  604. for (String path : list) {
  605. path = JGIT_REMOTE_DIR + "/" + path;
  606. s3.delete(bucket, path);
  607. }
  608. logger.debug("remote delete: " + JGIT_REMOTE_DIR);
  609. }
  610. /**
  611. * Verify if we can create/delete remote file.
  612. *
  613. * @throws Exception
  614. */
  615. static void remoteVerify() throws Exception {
  616. Properties props = Props.discover();
  617. String bucket = props.getProperty(Names.TEST_BUCKET);
  618. AmazonS3 s3 = new AmazonS3(props);
  619. String file = JGIT_USER + "-" + UUID.randomUUID().toString();
  620. String path = JGIT_REMOTE_DIR + "/" + file;
  621. s3.put(bucket, path, file.getBytes(UTF_8));
  622. s3.delete(bucket, path);
  623. }
  624. /**
  625. * Verify if any security provider published the algorithm.
  626. *
  627. * @param algorithm
  628. * @return result
  629. */
  630. static boolean isAlgorithmPresent(String algorithm) {
  631. Set<String> cipherSet = Security.getAlgorithms("Cipher");
  632. for (String source : cipherSet) {
  633. // Standard names are not case-sensitive.
  634. // http://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html
  635. String target = algorithm.toUpperCase(Locale.ROOT);
  636. if (source.equalsIgnoreCase(target)) {
  637. return true;
  638. }
  639. }
  640. return false;
  641. }
  642. static boolean isAlgorithmPresent(Properties props) {
  643. String profile = props.getProperty(AmazonS3.Keys.CRYPTO_ALG);
  644. String version = props.getProperty(AmazonS3.Keys.CRYPTO_VER,
  645. WalkEncryption.Vals.DEFAULT_VERS);
  646. String cryptoAlgo;
  647. String keyAlgo;
  648. switch (version) {
  649. case WalkEncryption.Vals.DEFAULT_VERS:
  650. case WalkEncryption.JGitV1.VERSION:
  651. cryptoAlgo = profile;
  652. keyAlgo = profile;
  653. break;
  654. case WalkEncryption.JGitV2.VERSION:
  655. cryptoAlgo = props
  656. .getProperty(profile + WalkEncryption.Keys.X_ALGO);
  657. keyAlgo = props
  658. .getProperty(profile + WalkEncryption.Keys.X_KEY_ALGO);
  659. break;
  660. default:
  661. return false;
  662. }
  663. try {
  664. InsecureCipherFactory.create(cryptoAlgo);
  665. SecretKeyFactory.getInstance(keyAlgo);
  666. return true;
  667. } catch (Throwable e) {
  668. return false;
  669. }
  670. }
  671. /**
  672. * Verify if JRE security policy allows the algorithm.
  673. *
  674. * @param algorithm
  675. * @return result
  676. */
  677. static boolean isAlgorithmAllowed(String algorithm) {
  678. try {
  679. WalkEncryption crypto = new WalkEncryption.JetS3tV2(
  680. algorithm, JGIT_PASS);
  681. verifyCrypto(crypto);
  682. return true;
  683. } catch (IOException e) {
  684. return false; // Encryption failure.
  685. } catch (GeneralSecurityException e) {
  686. throw new Error(e); // Construction failure.
  687. }
  688. }
  689. static boolean isAlgorithmAllowed(Properties props) {
  690. try {
  691. WalkEncryption.instance(props);
  692. return true;
  693. } catch (GeneralSecurityException e) {
  694. return false;
  695. }
  696. }
  697. /**
  698. * Verify round trip encryption.
  699. *
  700. * @param crypto
  701. * @throws IOException
  702. */
  703. static void verifyCrypto(WalkEncryption crypto) throws IOException {
  704. String charset = "UTF-8";
  705. String sourceText = "secret-message Свобода 老子";
  706. String targetText;
  707. byte[] cipherText;
  708. {
  709. byte[] origin = sourceText.getBytes(charset);
  710. ByteArrayOutputStream target = new ByteArrayOutputStream();
  711. try (OutputStream source = crypto.encrypt(target)) {
  712. source.write(origin);
  713. source.flush();
  714. }
  715. cipherText = target.toByteArray();
  716. }
  717. {
  718. InputStream source = new ByteArrayInputStream(cipherText);
  719. InputStream target = crypto.decrypt(source);
  720. ByteArrayOutputStream result = new ByteArrayOutputStream();
  721. transferStream(target, result);
  722. targetText = result.toString(charset);
  723. }
  724. assertEquals(sourceText, targetText);
  725. }
  726. /**
  727. * Algorithm is testable when it is present and allowed by policy.
  728. *
  729. * @param algorithm
  730. * @return result
  731. */
  732. static boolean isAlgorithmTestable(String algorithm) {
  733. return isAlgorithmPresent(algorithm)
  734. && isAlgorithmAllowed(algorithm);
  735. }
  736. static boolean isAlgorithmTestable(Properties props) {
  737. return isAlgorithmPresent(props) && isAlgorithmAllowed(props);
  738. }
  739. /**
  740. * Log algorithm, provider, testability.
  741. *
  742. * @param algorithm
  743. * @throws Exception
  744. */
  745. static void reportAlgorithmStatus(String algorithm) throws Exception {
  746. final boolean present = isAlgorithmPresent(algorithm);
  747. final boolean allowed = present && isAlgorithmAllowed(algorithm);
  748. final String provider = present ? securityProviderName(algorithm)
  749. : "N/A";
  750. String status = "Algorithm: " + algorithm + " @ " + provider + "; "
  751. + "present/allowed : " + present + "/" + allowed;
  752. if (allowed) {
  753. logger.info("Testing " + status);
  754. } else {
  755. logger.warn("Missing " + status);
  756. }
  757. }
  758. static void reportAlgorithmStatus(Properties props) throws Exception {
  759. final boolean present = isAlgorithmPresent(props);
  760. final boolean allowed = present && isAlgorithmAllowed(props);
  761. String profile = props.getProperty(AmazonS3.Keys.CRYPTO_ALG);
  762. String version = props.getProperty(AmazonS3.Keys.CRYPTO_VER);
  763. StringBuilder status = new StringBuilder();
  764. status.append(" Version: " + version);
  765. status.append(" Profile: " + profile);
  766. status.append(" Present: " + present);
  767. status.append(" Allowed: " + allowed);
  768. if (allowed) {
  769. logger.info("Testing " + status);
  770. } else {
  771. logger.warn("Missing " + status);
  772. }
  773. }
  774. /**
  775. * Verify if we can perform remote tests.
  776. *
  777. * @return result
  778. */
  779. static boolean isTestConfigPresent() {
  780. try {
  781. Props.discover();
  782. return true;
  783. } catch (Throwable e) {
  784. return false;
  785. }
  786. }
  787. static void reportTestConfigPresent() {
  788. if (isTestConfigPresent()) {
  789. logger.info("Amazon S3 test configuration is present.");
  790. } else {
  791. logger.error(
  792. "Amazon S3 test configuration is missing, tests will not run.");
  793. }
  794. }
  795. /**
  796. * Log public address of CI.
  797. *
  798. * @throws Exception
  799. */
  800. static void reportPublicAddress() throws Exception {
  801. logger.info("Public address: " + publicAddress());
  802. }
  803. /**
  804. * BouncyCastle provider class.
  805. *
  806. * Needs extra dependency, see pom.xml
  807. */
  808. // http://search.maven.org/#artifactdetails%7Corg.bouncycastle%7Cbcprov-jdk15on%7C1.52%7Cjar
  809. static final String PROVIDER_BC = "org.bouncycastle.jce.provider.BouncyCastleProvider";
  810. /**
  811. * Load BouncyCastle provider if present.
  812. */
  813. static void loadBouncyCastle() {
  814. try {
  815. Class<?> provider = Class.forName(PROVIDER_BC);
  816. Provider instance = (Provider) provider
  817. .getConstructor(new Class[] {})
  818. .newInstance(new Object[] {});
  819. Security.addProvider(instance);
  820. logger.info("Loaded " + PROVIDER_BC);
  821. } catch (Throwable e) {
  822. logger.warn("Failed to load " + PROVIDER_BC);
  823. }
  824. }
  825. static void reportLongTests() {
  826. if (permitLongTests()) {
  827. logger.info("Long running tests are enabled.");
  828. } else {
  829. logger.warn("Long running tests are disabled.");
  830. }
  831. }
  832. /**
  833. * Non-PBE algorithm, for error check.
  834. */
  835. static final String ALGO_ERROR = "PBKDF2WithHmacSHA1";
  836. /**
  837. * Default JetS3t algorithm present in most JRE.
  838. */
  839. static final String ALGO_JETS3T = "PBEWithMD5AndDES";
  840. /**
  841. * Minimal strength AES based algorithm present in most JRE.
  842. */
  843. static final String ALGO_MINIMAL_AES = "PBEWithHmacSHA1AndAES_128";
  844. /**
  845. * Selected non-AES algorithm present in BouncyCastle provider.
  846. */
  847. static final String ALGO_BOUNCY_CASTLE_CBC = "PBEWithSHAAndTwofish-CBC";
  848. //////////////////////////////////////////////////
  849. @BeforeClass
  850. public static void initialize() throws Exception {
  851. Transport.register(TransportAmazonS3.PROTO_S3);
  852. proxySetup();
  853. reportPolicy();
  854. reportLongTests();
  855. reportPublicAddress();
  856. reportTestConfigPresent();
  857. loadBouncyCastle();
  858. if (isTestConfigPresent()) {
  859. remoteCreate();
  860. }
  861. }
  862. @AfterClass
  863. public static void terminate() throws Exception {
  864. configDelete();
  865. folderDelete(JGIT_LOCAL_DIR);
  866. if (isTestConfigPresent()) {
  867. remoteDelete();
  868. }
  869. }
  870. @Before
  871. @Override
  872. public void setUp() throws Exception {
  873. super.setUp();
  874. }
  875. @After
  876. @Override
  877. public void tearDown() throws Exception {
  878. super.tearDown();
  879. }
  880. /**
  881. * Optional encrypted amazon remote JGIT life cycle test.
  882. *
  883. * @param props
  884. * @throws Exception
  885. */
  886. void cryptoTestIfCan(Properties props) throws Exception {
  887. reportAlgorithmStatus(props);
  888. assumeTrue(isTestConfigPresent());
  889. assumeTrue(isAlgorithmTestable(props));
  890. cryptoTest(props);
  891. }
  892. /**
  893. * Required encrypted amazon remote JGIT life cycle test.
  894. *
  895. * @param props
  896. * @throws Exception
  897. */
  898. void cryptoTest(Properties props) throws Exception {
  899. remoteDelete();
  900. configCreate(props);
  901. folderDelete(JGIT_LOCAL_DIR);
  902. String uri = amazonURI();
  903. // Local repositories.
  904. File dirOne = db.getWorkTree(); // Provided by setup.
  905. File dirTwo = new File(JGIT_LOCAL_DIR);
  906. // Local verification files.
  907. String nameStatic = "master.txt"; // Provided by setup.
  908. String nameDynamic = JGIT_USER + "-" + UUID.randomUUID().toString();
  909. String remote = "remote";
  910. RefSpec specs = new RefSpec("refs/heads/master:refs/heads/master");
  911. { // Push into remote from local one.
  912. StoredConfig config = db.getConfig();
  913. RemoteConfig remoteConfig = new RemoteConfig(config, remote);
  914. remoteConfig.addURI(new URIish(uri));
  915. remoteConfig.update(config);
  916. config.save();
  917. try (Git git = Git.open(dirOne)) {
  918. git.checkout().setName("master").call();
  919. git.push().setRemote(remote).setRefSpecs(specs).call();
  920. }
  921. File fileStatic = new File(dirOne, nameStatic);
  922. assertTrue("Provided by setup", fileStatic.exists());
  923. }
  924. { // Clone from remote into local two.
  925. File fileStatic = new File(dirTwo, nameStatic);
  926. assertFalse("Not Provided by setup", fileStatic.exists());
  927. try (Git git = Git.cloneRepository().setURI(uri)
  928. .setDirectory(dirTwo).call()) {
  929. assertTrue("Provided by clone", fileStatic.exists());
  930. }
  931. }
  932. { // Verify static file content.
  933. File fileOne = new File(dirOne, nameStatic);
  934. File fileTwo = new File(dirTwo, nameStatic);
  935. verifyFileContent(fileOne, fileTwo);
  936. }
  937. { // Verify new file commit and push from local one.
  938. File fileDynamic = new File(dirOne, nameDynamic);
  939. assertFalse("Not Provided by setup", fileDynamic.exists());
  940. FileUtils.createNewFile(fileDynamic);
  941. textWrite(fileDynamic, nameDynamic);
  942. assertTrue("Provided by create", fileDynamic.exists());
  943. assertTrue("Need content to encrypt", fileDynamic.length() > 0);
  944. try (Git git = Git.open(dirOne)) {
  945. git.add().addFilepattern(nameDynamic).call();
  946. git.commit().setMessage(nameDynamic).call();
  947. git.push().setRemote(remote).setRefSpecs(specs).call();
  948. }
  949. }
  950. { // Verify new file pull from remote into local two.
  951. File fileDynamic = new File(dirTwo, nameDynamic);
  952. assertFalse("Not Provided by setup", fileDynamic.exists());
  953. try (Git git = Git.open(dirTwo)) {
  954. git.pull().call();
  955. }
  956. assertTrue("Provided by pull", fileDynamic.exists());
  957. }
  958. { // Verify dynamic file content.
  959. File fileOne = new File(dirOne, nameDynamic);
  960. File fileTwo = new File(dirTwo, nameDynamic);
  961. verifyFileContent(fileOne, fileTwo);
  962. }
  963. }
  964. }
  965. /**
  966. * Verify prerequisites.
  967. */
  968. @FixMethodOrder(MethodSorters.NAME_ASCENDING)
  969. public static class Required extends Base {
  970. @Test
  971. public void test_A1_ValidURI() throws Exception {
  972. assumeTrue(isTestConfigPresent());
  973. URIish uri = new URIish(amazonURI());
  974. assertTrue("uri=" + uri, TransportAmazonS3.PROTO_S3.canHandle(uri));
  975. }
  976. @Test(expected = Exception.class)
  977. public void test_A2_CryptoError() throws Exception {
  978. assumeTrue(isTestConfigPresent());
  979. Properties props = new Properties();
  980. props.put(AmazonS3.Keys.CRYPTO_ALG, ALGO_ERROR);
  981. props.put(AmazonS3.Keys.PASSWORD, JGIT_PASS);
  982. cryptoTest(props);
  983. }
  984. }
  985. /**
  986. * Test minimal set of algorithms.
  987. */
  988. @FixMethodOrder(MethodSorters.NAME_ASCENDING)
  989. public static class MinimalSet extends Base {
  990. @Test
  991. public void test_V0_Java7_JET() throws Exception {
  992. assumeTrue(isTestConfigPresent());
  993. Properties props = new Properties();
  994. props.put(AmazonS3.Keys.CRYPTO_ALG, ALGO_JETS3T);
  995. // Do not set version.
  996. props.put(AmazonS3.Keys.PASSWORD, JGIT_PASS);
  997. cryptoTestIfCan(props);
  998. }
  999. @Test
  1000. public void test_V1_Java7_GIT() throws Exception {
  1001. assumeTrue(isTestConfigPresent());
  1002. Properties props = new Properties();
  1003. props.put(AmazonS3.Keys.CRYPTO_ALG, ALGO_JETS3T);
  1004. props.put(AmazonS3.Keys.CRYPTO_VER, "1");
  1005. props.put(AmazonS3.Keys.PASSWORD, JGIT_PASS);
  1006. cryptoTestIfCan(props);
  1007. }
  1008. @Test
  1009. public void test_V2_Java7_AES() throws Exception {
  1010. assumeTrue(isTestConfigPresent());
  1011. // String profile = "default";
  1012. String profile = "AES/CBC/PKCS5Padding+PBKDF2WithHmacSHA1";
  1013. Properties props = new Properties();
  1014. props.put(AmazonS3.Keys.CRYPTO_ALG, profile);
  1015. props.put(AmazonS3.Keys.CRYPTO_VER, "2");
  1016. props.put(AmazonS3.Keys.PASSWORD, JGIT_PASS);
  1017. props.put(profile + WalkEncryption.Keys.X_ALGO, "AES/CBC/PKCS5Padding");
  1018. props.put(profile + WalkEncryption.Keys.X_KEY_ALGO, "PBKDF2WithHmacSHA1");
  1019. props.put(profile + WalkEncryption.Keys.X_KEY_SIZE, "128");
  1020. props.put(profile + WalkEncryption.Keys.X_KEY_ITER, "10000");
  1021. props.put(profile + WalkEncryption.Keys.X_KEY_SALT, "e2 55 89 67 8e 8d e8 4c");
  1022. cryptoTestIfCan(props);
  1023. }
  1024. @Test
  1025. public void test_V2_Java8_PBE_AES() throws Exception {
  1026. assumeTrue(isTestConfigPresent());
  1027. String profile = "PBEWithHmacSHA512AndAES_256";
  1028. Properties props = new Properties();
  1029. props.put(AmazonS3.Keys.CRYPTO_ALG, profile);
  1030. props.put(AmazonS3.Keys.CRYPTO_VER, "2");
  1031. props.put(AmazonS3.Keys.PASSWORD, JGIT_PASS);
  1032. props.put(profile + WalkEncryption.Keys.X_ALGO, "PBEWithHmacSHA512AndAES_256");
  1033. props.put(profile + WalkEncryption.Keys.X_KEY_ALGO, "PBEWithHmacSHA512AndAES_256");
  1034. props.put(profile + WalkEncryption.Keys.X_KEY_SIZE, "256");
  1035. props.put(profile + WalkEncryption.Keys.X_KEY_ITER, "10000");
  1036. props.put(profile + WalkEncryption.Keys.X_KEY_SALT, "e2 55 89 67 8e 8d e8 4c");
  1037. policySetup(false);
  1038. cryptoTestIfCan(props);
  1039. }
  1040. }
  1041. /**
  1042. * Test all present and allowed PBE algorithms.
  1043. */
  1044. // https://github.com/junit-team/junit/wiki/Parameterized-tests
  1045. @RunWith(Parameterized.class)
  1046. @FixMethodOrder(MethodSorters.NAME_ASCENDING)
  1047. public static class TestablePBE extends Base {
  1048. @Parameters(name = "Profile: {0} Version: {1}")
  1049. public static Collection<Object[]> argsList() {
  1050. List<String> algorithmList = new ArrayList<>();
  1051. algorithmList.addAll(cryptoCipherListPBE());
  1052. List<String> versionList = new ArrayList<>();
  1053. versionList.add("0");
  1054. versionList.add("1");
  1055. return product(algorithmList, versionList);
  1056. }
  1057. final String profile;
  1058. final String version;
  1059. final String password = JGIT_PASS;
  1060. public TestablePBE(String profile, String version) {
  1061. this.profile = profile;
  1062. this.version = version;
  1063. }
  1064. @Test
  1065. public void testCrypto() throws Exception {
  1066. assumeTrue(permitLongTests());
  1067. Properties props = new Properties();
  1068. props.put(AmazonS3.Keys.CRYPTO_ALG, profile);
  1069. props.put(AmazonS3.Keys.CRYPTO_VER, version);
  1070. props.put(AmazonS3.Keys.PASSWORD, password);
  1071. cryptoTestIfCan(props);
  1072. }
  1073. }
  1074. /**
  1075. * Test all present and allowed transformation algorithms.
  1076. */
  1077. // https://github.com/junit-team/junit/wiki/Parameterized-tests
  1078. @RunWith(Parameterized.class)
  1079. @FixMethodOrder(MethodSorters.NAME_ASCENDING)
  1080. public static class TestableTransformation extends Base {
  1081. @Parameters(name = "Profile: {0} Version: {1}")
  1082. public static Collection<Object[]> argsList() {
  1083. List<String> algorithmList = new ArrayList<>();
  1084. algorithmList.addAll(cryptoCipherListTrans());
  1085. List<String> versionList = new ArrayList<>();
  1086. versionList.add("1");
  1087. return product(algorithmList, versionList);
  1088. }
  1089. final String profile;
  1090. final String version;
  1091. final String password = JGIT_PASS;
  1092. public TestableTransformation(String profile, String version) {
  1093. this.profile = profile;
  1094. this.version = version;
  1095. }
  1096. @Test
  1097. public void testCrypto() throws Exception {
  1098. assumeTrue(permitLongTests());
  1099. Properties props = new Properties();
  1100. props.put(AmazonS3.Keys.CRYPTO_ALG, profile);
  1101. props.put(AmazonS3.Keys.CRYPTO_VER, version);
  1102. props.put(AmazonS3.Keys.PASSWORD, password);
  1103. cryptoTestIfCan(props);
  1104. }
  1105. }
  1106. }