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

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