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.

SshTestHarness.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. /*
  2. * Copyright (C) 2018, 2020 Thomas Wolf <thomas.wolf@paranor.ch> 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.junit.ssh;
  11. import static org.junit.Assert.assertEquals;
  12. import static org.junit.Assert.assertFalse;
  13. import static org.junit.Assert.assertNotEquals;
  14. import static org.junit.Assert.assertNotNull;
  15. import static org.junit.Assert.assertTrue;
  16. import java.io.BufferedWriter;
  17. import java.io.File;
  18. import java.io.FileOutputStream;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.OutputStream;
  22. import java.nio.charset.StandardCharsets;
  23. import java.nio.file.Files;
  24. import java.security.KeyPair;
  25. import java.security.KeyPairGenerator;
  26. import java.security.PrivateKey;
  27. import java.util.ArrayList;
  28. import java.util.Arrays;
  29. import java.util.Base64;
  30. import java.util.Collections;
  31. import java.util.Iterator;
  32. import java.util.List;
  33. import org.apache.sshd.common.config.keys.PublicKeyEntry;
  34. import org.eclipse.jgit.api.CloneCommand;
  35. import org.eclipse.jgit.api.Git;
  36. import org.eclipse.jgit.api.PushCommand;
  37. import org.eclipse.jgit.api.ResetCommand.ResetType;
  38. import org.eclipse.jgit.errors.UnsupportedCredentialItem;
  39. import org.eclipse.jgit.junit.RepositoryTestCase;
  40. import org.eclipse.jgit.lib.Constants;
  41. import org.eclipse.jgit.lib.Repository;
  42. import org.eclipse.jgit.revwalk.RevCommit;
  43. import org.eclipse.jgit.transport.CredentialItem;
  44. import org.eclipse.jgit.transport.CredentialsProvider;
  45. import org.eclipse.jgit.transport.PushResult;
  46. import org.eclipse.jgit.transport.RemoteRefUpdate;
  47. import org.eclipse.jgit.transport.SshSessionFactory;
  48. import org.eclipse.jgit.transport.URIish;
  49. import org.eclipse.jgit.util.FS;
  50. import org.junit.After;
  51. /**
  52. * Root class for ssh tests. Sets up the ssh test server. A set of pre-computed
  53. * keys for testing is provided in the bundle and can be used in test cases via
  54. * {@link #copyTestResource(String, File)}. These test key files names have four
  55. * components, separated by a single underscore: "id", the algorithm, the bits
  56. * (if variable), and the password if the private key is encrypted. For instance
  57. * "{@code id_ecdsa_384_testpass}" is an encrypted ECDSA-384 key. The passphrase
  58. * to decrypt is "testpass". The key "{@code id_ecdsa_384}" is the same but
  59. * unencrypted. All keys were generated and encrypted via ssh-keygen. Note that
  60. * DSA and ec25519 have no "bits" component. Available keys are listed in
  61. * {@link SshTestBase#KEY_RESOURCES}.
  62. */
  63. public abstract class SshTestHarness extends RepositoryTestCase {
  64. protected static final String TEST_USER = "testuser";
  65. protected File sshDir;
  66. protected File privateKey1;
  67. protected File privateKey2;
  68. protected File publicKey1;
  69. protected File publicKey2;
  70. protected SshTestGitServer server;
  71. private SshSessionFactory factory;
  72. protected int testPort;
  73. protected File knownHosts;
  74. private File homeDir;
  75. @Override
  76. public void setUp() throws Exception {
  77. super.setUp();
  78. writeTrashFile("file.txt", "something");
  79. try (Git git = new Git(db)) {
  80. git.add().addFilepattern("file.txt").call();
  81. git.commit().setMessage("Initial commit").call();
  82. }
  83. mockSystemReader.setProperty("user.home",
  84. getTemporaryDirectory().getAbsolutePath());
  85. mockSystemReader.setProperty("HOME",
  86. getTemporaryDirectory().getAbsolutePath());
  87. homeDir = FS.DETECTED.userHome();
  88. FS.DETECTED.setUserHome(getTemporaryDirectory().getAbsoluteFile());
  89. sshDir = new File(getTemporaryDirectory(), ".ssh");
  90. assertTrue(sshDir.mkdir());
  91. File serverDir = new File(getTemporaryDirectory(), "srv");
  92. assertTrue(serverDir.mkdir());
  93. // Create two key pairs. Let's not call them "id_rsa".
  94. KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
  95. generator.initialize(2048);
  96. privateKey1 = new File(sshDir, "first_key");
  97. privateKey2 = new File(sshDir, "second_key");
  98. publicKey1 = createKeyPair(generator.generateKeyPair(), privateKey1);
  99. publicKey2 = createKeyPair(generator.generateKeyPair(), privateKey2);
  100. // Create a host key
  101. KeyPair hostKey = generator.generateKeyPair();
  102. // Start a server with our test user and the first key.
  103. server = new SshTestGitServer(TEST_USER, publicKey1.toPath(), db,
  104. hostKey);
  105. testPort = server.start();
  106. assertTrue(testPort > 0);
  107. knownHosts = new File(sshDir, "known_hosts");
  108. StringBuilder knownHostsLine = new StringBuilder();
  109. knownHostsLine.append("[localhost]:").append(testPort).append(' ');
  110. PublicKeyEntry.appendPublicKeyEntry(knownHostsLine,
  111. hostKey.getPublic());
  112. Files.write(knownHosts.toPath(),
  113. Collections.singleton(knownHostsLine.toString()));
  114. factory = createSessionFactory();
  115. SshSessionFactory.setInstance(factory);
  116. }
  117. private static File createKeyPair(KeyPair newKey, File privateKeyFile)
  118. throws Exception {
  119. // Write PKCS#8 PEM unencrypted. Both JSch and sshd can read that.
  120. PrivateKey privateKey = newKey.getPrivate();
  121. String format = privateKey.getFormat();
  122. if (!"PKCS#8".equalsIgnoreCase(format)) {
  123. throw new IOException("Cannot write " + privateKey.getAlgorithm()
  124. + " key in " + format + " format");
  125. }
  126. try (BufferedWriter writer = Files.newBufferedWriter(
  127. privateKeyFile.toPath(), StandardCharsets.US_ASCII)) {
  128. writer.write("-----BEGIN PRIVATE KEY-----");
  129. writer.newLine();
  130. write(writer, privateKey.getEncoded(), 64);
  131. writer.write("-----END PRIVATE KEY-----");
  132. writer.newLine();
  133. }
  134. File publicKeyFile = new File(privateKeyFile.getParentFile(),
  135. privateKeyFile.getName() + ".pub");
  136. StringBuilder builder = new StringBuilder();
  137. PublicKeyEntry.appendPublicKeyEntry(builder, newKey.getPublic());
  138. builder.append(' ').append(TEST_USER);
  139. try (OutputStream out = new FileOutputStream(publicKeyFile)) {
  140. out.write(builder.toString().getBytes(StandardCharsets.US_ASCII));
  141. }
  142. return publicKeyFile;
  143. }
  144. private static void write(BufferedWriter out, byte[] bytes, int lineLength)
  145. throws IOException {
  146. String data = Base64.getEncoder().encodeToString(bytes);
  147. int last = data.length();
  148. for (int i = 0; i < last; i += lineLength) {
  149. if (i + lineLength <= last) {
  150. out.write(data.substring(i, i + lineLength));
  151. } else {
  152. out.write(data.substring(i));
  153. }
  154. out.newLine();
  155. }
  156. Arrays.fill(bytes, (byte) 0);
  157. }
  158. /**
  159. * Creates a new known_hosts file with one entry for the given host and port
  160. * taken from the given public key file.
  161. *
  162. * @param file
  163. * to write the known_hosts file to
  164. * @param host
  165. * for the entry
  166. * @param port
  167. * for the entry
  168. * @param publicKey
  169. * to use
  170. * @return the public-key part of the line
  171. * @throws IOException
  172. */
  173. protected static String createKnownHostsFile(File file, String host,
  174. int port, File publicKey) throws IOException {
  175. List<String> lines = Files.readAllLines(publicKey.toPath(),
  176. StandardCharsets.UTF_8);
  177. assertEquals("Public key has too many lines", 1, lines.size());
  178. String pubKey = lines.get(0);
  179. // Strip off the comment.
  180. String[] parts = pubKey.split("\\s+");
  181. assertTrue("Unexpected key content",
  182. parts.length == 2 || parts.length == 3);
  183. String keyPart = parts[0] + ' ' + parts[1];
  184. String line = '[' + host + "]:" + port + ' ' + keyPart;
  185. Files.write(file.toPath(), Collections.singletonList(line));
  186. return keyPart;
  187. }
  188. /**
  189. * Checks whether there is a line for the given host and port that also
  190. * matches the given key part in the list of lines.
  191. *
  192. * @param host
  193. * to look for
  194. * @param port
  195. * to look for
  196. * @param keyPart
  197. * to look for
  198. * @param lines
  199. * to look in
  200. * @return {@code true} if found, {@code false} otherwise
  201. */
  202. protected boolean hasHostKey(String host, int port, String keyPart,
  203. List<String> lines) {
  204. String h = '[' + host + "]:" + port;
  205. return lines.stream()
  206. .anyMatch(l -> l.contains(h) && l.contains(keyPart));
  207. }
  208. @After
  209. public void shutdownServer() throws Exception {
  210. if (server != null) {
  211. server.stop();
  212. server = null;
  213. }
  214. FS.DETECTED.setUserHome(homeDir);
  215. SshSessionFactory.setInstance(null);
  216. factory = null;
  217. }
  218. protected abstract SshSessionFactory createSessionFactory();
  219. protected SshSessionFactory getSessionFactory() {
  220. return factory;
  221. }
  222. protected abstract void installConfig(String... config);
  223. /**
  224. * Copies a test data file contained in the test bundle to the given file.
  225. * Equivalent to {@link #copyTestResource(Class, String, File)} with
  226. * {@code SshTestHarness.class} as first parameter.
  227. *
  228. * @param resourceName
  229. * of the test resource to copy
  230. * @param to
  231. * file to copy the resource to
  232. * @throws IOException
  233. * if the resource cannot be copied
  234. */
  235. protected void copyTestResource(String resourceName, File to)
  236. throws IOException {
  237. copyTestResource(SshTestHarness.class, resourceName, to);
  238. }
  239. /**
  240. * Copies a test data file contained in the test bundle to the given file,
  241. * using {@link Class#getResourceAsStream(String)} to get the test resource.
  242. *
  243. * @param loader
  244. * {@link Class} to use to load the resource
  245. * @param resourceName
  246. * of the test resource to copy
  247. * @param to
  248. * file to copy the resource to
  249. * @throws IOException
  250. * if the resource cannot be copied
  251. */
  252. protected void copyTestResource(Class<?> loader, String resourceName,
  253. File to) throws IOException {
  254. try (InputStream in = loader.getResourceAsStream(resourceName)) {
  255. Files.copy(in, to.toPath());
  256. }
  257. }
  258. protected File cloneWith(String uri, File to, CredentialsProvider provider,
  259. String... config) throws Exception {
  260. installConfig(config);
  261. CloneCommand clone = Git.cloneRepository().setCloneAllBranches(true)
  262. .setDirectory(to).setURI(uri);
  263. if (provider != null) {
  264. clone.setCredentialsProvider(provider);
  265. }
  266. try (Git git = clone.call()) {
  267. Repository repo = git.getRepository();
  268. assertNotNull(repo.resolve("master"));
  269. assertNotEquals(db.getWorkTree(),
  270. git.getRepository().getWorkTree());
  271. assertTrue(new File(git.getRepository().getWorkTree(), "file.txt")
  272. .exists());
  273. return repo.getWorkTree();
  274. }
  275. }
  276. protected void pushTo(File localClone) throws Exception {
  277. pushTo(null, localClone);
  278. }
  279. protected void pushTo(CredentialsProvider provider, File localClone)
  280. throws Exception {
  281. RevCommit commit;
  282. File newFile = null;
  283. try (Git git = Git.open(localClone)) {
  284. // Write a new file and modify a file.
  285. Repository local = git.getRepository();
  286. newFile = File.createTempFile("new", "sshtest",
  287. local.getWorkTree());
  288. write(newFile, "something new");
  289. File existingFile = new File(local.getWorkTree(), "file.txt");
  290. write(existingFile, "something else");
  291. git.add().addFilepattern("file.txt")
  292. .addFilepattern(newFile.getName())
  293. .call();
  294. commit = git.commit().setMessage("Local commit").call();
  295. // Push
  296. PushCommand push = git.push().setPushAll();
  297. if (provider != null) {
  298. push.setCredentialsProvider(provider);
  299. }
  300. Iterable<PushResult> results = push.call();
  301. for (PushResult result : results) {
  302. for (RemoteRefUpdate u : result.getRemoteUpdates()) {
  303. assertEquals(
  304. "Could not update " + u.getRemoteName() + ' '
  305. + u.getMessage(),
  306. RemoteRefUpdate.Status.OK, u.getStatus());
  307. }
  308. }
  309. }
  310. // Now check "master" in the remote repo directly:
  311. assertEquals("Unexpected remote commit", commit, db.resolve("master"));
  312. assertEquals("Unexpected remote commit", commit,
  313. db.resolve(Constants.HEAD));
  314. File remoteFile = new File(db.getWorkTree(), newFile.getName());
  315. assertFalse("File should not exist on remote", remoteFile.exists());
  316. try (Git git = new Git(db)) {
  317. git.reset().setMode(ResetType.HARD).setRef(Constants.HEAD).call();
  318. }
  319. assertTrue("File does not exist on remote", remoteFile.exists());
  320. checkFile(remoteFile, "something new");
  321. }
  322. protected static class TestCredentialsProvider extends CredentialsProvider {
  323. private final List<String> stringStore;
  324. private final Iterator<String> strings;
  325. public TestCredentialsProvider(String... strings) {
  326. if (strings == null || strings.length == 0) {
  327. stringStore = Collections.emptyList();
  328. } else {
  329. stringStore = Arrays.asList(strings);
  330. }
  331. this.strings = stringStore.iterator();
  332. }
  333. @Override
  334. public boolean isInteractive() {
  335. return true;
  336. }
  337. @Override
  338. public boolean supports(CredentialItem... items) {
  339. return true;
  340. }
  341. @Override
  342. public boolean get(URIish uri, CredentialItem... items)
  343. throws UnsupportedCredentialItem {
  344. System.out.println("URI: " + uri);
  345. for (CredentialItem item : items) {
  346. System.out.println(item.getClass().getSimpleName() + ' '
  347. + item.getPromptText());
  348. }
  349. logItems(uri, items);
  350. for (CredentialItem item : items) {
  351. if (item instanceof CredentialItem.InformationalMessage) {
  352. continue;
  353. }
  354. if (item instanceof CredentialItem.YesNoType) {
  355. ((CredentialItem.YesNoType) item).setValue(true);
  356. } else if (item instanceof CredentialItem.CharArrayType) {
  357. if (strings.hasNext()) {
  358. ((CredentialItem.CharArrayType) item)
  359. .setValue(strings.next().toCharArray());
  360. } else {
  361. return false;
  362. }
  363. } else if (item instanceof CredentialItem.StringType) {
  364. if (strings.hasNext()) {
  365. ((CredentialItem.StringType) item)
  366. .setValue(strings.next());
  367. } else {
  368. return false;
  369. }
  370. } else {
  371. return false;
  372. }
  373. }
  374. return true;
  375. }
  376. private List<LogEntry> log = new ArrayList<>();
  377. private void logItems(URIish uri, CredentialItem... items) {
  378. log.add(new LogEntry(uri, Arrays.asList(items)));
  379. }
  380. public List<LogEntry> getLog() {
  381. return log;
  382. }
  383. }
  384. protected static class LogEntry {
  385. private URIish uri;
  386. private List<CredentialItem> items;
  387. public LogEntry(URIish uri, List<CredentialItem> items) {
  388. this.uri = uri;
  389. this.items = items;
  390. }
  391. public URIish getURIish() {
  392. return uri;
  393. }
  394. public List<CredentialItem> getItems() {
  395. return items;
  396. }
  397. }
  398. }