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