org.eclipse.jgit.util.FS Java Examples

The following examples show how to use org.eclipse.jgit.util.FS. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MultiUserSshSessionFactory.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
private Session createSession(CredentialsProvider credentialsProvider,
                              FS fs, String user, final String pass, String host, int port,
                              final OpenSshConfig.Host hc) throws JSchException {
    final Session session = createSession(credentialsProvider, hc, user, host, port, fs);
    // We retry already in getSession() method. JSch must not retry
    // on its own.
    session.setConfig("MaxAuthTries", "1"); //$NON-NLS-1$ //$NON-NLS-2$
    if (pass != null)
        session.setPassword(pass);
    final String strictHostKeyCheckingPolicy = hc
            .getStrictHostKeyChecking();
    if (strictHostKeyCheckingPolicy != null)
        session.setConfig("StrictHostKeyChecking", //$NON-NLS-1$
                strictHostKeyCheckingPolicy);
    final String pauth = hc.getPreferredAuthentications();
    if (pauth != null)
        session.setConfig("PreferredAuthentications", pauth); //$NON-NLS-1$
    if (credentialsProvider != null && !(credentialsProvider instanceof PrivateKeyCredentialsProvider)
            && (!hc.isBatchMode() || !credentialsProvider.isInteractive())) {
        session.setUserInfo(new CredentialsProviderUserInfo(session,
                credentialsProvider));
    }
    configure(hc, session);
    return session;
}
 
Example #2
Source File: MultiUserSshSessionFactory.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static void knownHosts(final JSch sch, FS fs) throws JSchException {
    final File home = fs.userHome();
    if (home == null)
        return;
    final File known_hosts = new File(new File(home, ".ssh"), "known_hosts"); //$NON-NLS-1$ //$NON-NLS-2$
    try {
        final FileInputStream in = new FileInputStream(known_hosts);
        try {
            sch.setKnownHosts(in);
        } finally {
            in.close();
        }
    } catch (FileNotFoundException none) {
        // Oh well. They don't have a known hosts in home.
    } catch (IOException err) {
        // Oh well. They don't have a known hosts in home.
    }
}
 
Example #3
Source File: StudioNodeSyncBaseTask.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
protected <T extends TransportCommand> void configurePrivateKeyAuthentication(
        ClusterMember remoteNode, T gitCommand, TextEncryptor encryptor, final Path tempKey)
        throws CryptoException, IOException  {
    String privateKey = encryptor.decrypt(remoteNode.getGitPrivateKey());
    try {
        Files.write(tempKey, privateKey.getBytes());
    } catch (IOException e) {
        throw new IOException("Failed to write private key for SSH connection to temp location", e);
    }

    tempKey.toFile().deleteOnExit();

    gitCommand.setTransportConfigCallback(transport -> {
        SshTransport sshTransport = (SshTransport)transport;
        sshTransport.setSshSessionFactory(new StrictHostCheckingOffSshSessionFactory() {

            @Override
            protected JSch createDefaultJSch(FS fs) throws JSchException {
                JSch defaultJSch = super.createDefaultJSch(fs);
                defaultJSch.addIdentity(tempKey.toAbsolutePath().toString());
                return defaultJSch;
            }

        });
    });
}
 
Example #4
Source File: GitContentRepositoryHelper.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
private SshSessionFactory getSshSessionFactory(String remotePrivateKey, final Path tempKey) {
    try {

        Files.write(tempKey, remotePrivateKey.getBytes());
        SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
            @Override
            protected void configure(OpenSshConfig.Host hc, Session session) {
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
            }

            @Override
            protected JSch createDefaultJSch(FS fs) throws JSchException {
                JSch defaultJSch = super.createDefaultJSch(fs);
                defaultJSch.addIdentity(tempKey.toAbsolutePath().toString());
                return defaultJSch;
            }
        };
        return sshSessionFactory;
    } catch (IOException e) {
        logger.error("Failed to create private key for SSH connection.", e);
    }
    return null;
}
 
Example #5
Source File: CustomJschConfigSessionFactory.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
@Override
protected JSch createDefaultJSch(FS fs) throws JSchException {

    JSch def = super.createDefaultJSch(fs);
    String keyName = ServerConfiguration.getInstance().
            getFirstProperty(GitDeploymentSynchronizerConstants.SSH_PRIVATE_KEY_NAME);
    String keyPath = ServerConfiguration.getInstance().
            getFirstProperty(GitDeploymentSynchronizerConstants.SSH_PRIVATE_KEY_PATH);

    if (keyName == null || keyName.isEmpty())
        keyName = GitDeploymentSynchronizerConstants.SSH_KEY;

    if (keyPath == null || keyPath.isEmpty())
        keyPath = System.getProperty("user.home") + "/" + GitDeploymentSynchronizerConstants.SSH_KEY_DIRECTORY;

    if (keyPath.endsWith("/"))
        def.addIdentity(keyPath + keyName);
    else
        def.addIdentity(keyPath + "/" + keyName);

    return def;
}
 
Example #6
Source File: GenericBasedGitVcsOperator.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * New transport callback for ssh-key authenticate credentials.
 *
 * @param identity
 * @return
 * @throws Exception
 * @see {@link TransportConfigCallback}
 */
private TransportConfigCallback newTransportConfigCallback(byte[] identity) throws Exception {
    return new TransportConfigCallback() {
        @Override
        public void configure(Transport transport) {
            SshTransport sshTransport = (SshTransport) transport;
            sshTransport.setSshSessionFactory(new JschConfigSessionFactory() {
                @Override
                protected void configure(OpenSshConfig.Host hc, Session session) {
                    session.setConfig("StrictHostKeyChecking", "no");
                    // session.setPort(2022);
                }

                @Override
                protected JSch createDefaultJSch(FS fs) throws JSchException {
                    JSch jsch = super.createDefaultJSch(fs);
                    jsch.removeAllIdentity();
                    // jsch.addIdentity("/Users/vjay/.ssh/id_rsa");
                    jsch.getIdentityRepository().add(identity);
                    return jsch;
                }
            });
        }
    };
}
 
Example #7
Source File: ResolveMerger.java    From onedev with MIT License 6 votes vote down vote up
/**
 * Writes merged file content to the working tree.
 *
 * @param rawMerged
 *            the raw merged content
 * @param attributes
 *            the files .gitattributes entries
 * @return the working tree file to which the merged content was written.
 * @throws FileNotFoundException
 * @throws IOException
 */
private File writeMergedFile(TemporaryBuffer rawMerged,
		Attributes attributes)
		throws FileNotFoundException, IOException {
	File workTree = nonNullRepo().getWorkTree();
	FS fs = nonNullRepo().getFS();
	File of = new File(workTree, tw.getPathString());
	File parentFolder = of.getParentFile();
	if (!fs.exists(parentFolder)) {
		parentFolder.mkdirs();
	}
	EolStreamType streamType = EolStreamTypeUtil.detectStreamType(
			OperationType.CHECKOUT_OP, workingTreeOptions,
			attributes);
	try (OutputStream os = EolStreamTypeUtil.wrapOutputStream(
			new BufferedOutputStream(new FileOutputStream(of)),
			streamType)) {
		rawMerged.writeTo(os, null);
	}
	return of;
}
 
Example #8
Source File: PropertyBasedSshSessionFactory.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Override
protected Session createSession(Host hc, String user, String host, int port, FS fs)
		throws JSchException {
	if (this.sshKeysByHostname.containsKey(host)) {
		JGitEnvironmentProperties sshUriProperties = this.sshKeysByHostname.get(host);
		this.jSch.addIdentity(host, sshUriProperties.getPrivateKey().getBytes(), null,
				null);
		if (sshUriProperties.getKnownHostsFile() != null) {
			this.jSch.setKnownHosts(sshUriProperties.getKnownHostsFile());
		}
		if (sshUriProperties.getHostKey() != null) {
			HostKey hostkey = new HostKey(host,
					Base64.decode(sshUriProperties.getHostKey()));
			this.jSch.getHostKeyRepository().add(hostkey, null);
		}
		return this.jSch.getSession(user, host, port);
	}
	throw new JSchException("no keys configured for hostname " + host);
}
 
Example #9
Source File: StudioNodeSyncGlobalRepoTask.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
private <T extends TransportCommand> void configurePrivateKeyAuthentication(
        ClusterMember remoteNode, T gitCommand, TextEncryptor encryptor, final Path tempKey)
        throws CryptoException, IOException  {
    String privateKey = encryptor.decrypt(remoteNode.getGitPrivateKey());
    try {
        Files.write(tempKey, privateKey.getBytes());
    } catch (IOException e) {
        throw new IOException("Failed to write private key for SSH connection to temp location", e);
    }

    tempKey.toFile().deleteOnExit();

    gitCommand.setTransportConfigCallback(transport -> {
        SshTransport sshTransport = (SshTransport)transport;
        sshTransport.setSshSessionFactory(new StrictHostCheckingOffSshSessionFactory() {

            @Override
            protected JSch createDefaultJSch(FS fs) throws JSchException {
                JSch defaultJSch = super.createDefaultJSch(fs);
                defaultJSch.addIdentity(tempKey.toAbsolutePath().toString());
                return defaultJSch;
            }

        });
    });
}
 
Example #10
Source File: GitContentRepository.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
private SshSessionFactory getSshSessionFactory(String privateKey, final Path tempKey)  {
    try {
        Files.write(tempKey, privateKey.getBytes());
        SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
            @Override
            protected void configure(OpenSshConfig.Host hc, Session session) {
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
            }

            @Override
            protected JSch createDefaultJSch(FS fs) throws JSchException {
                JSch defaultJSch = new JSch();
                defaultJSch.addIdentity(tempKey.toAbsolutePath().toString());
                return defaultJSch;
            }
        };
        return sshSessionFactory;
    } catch (IOException e) {
        logger.error("Failed to create private key for SSH connection.", e);
    }
    return null;
}
 
Example #11
Source File: GitUtils.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the file representing the Git repository directory for the given file path or any of its parent in the filesystem. If the file doesn't exits, is
 * not a Git repository or an error occurred while transforming the given path into a store <code>null</code> is returned.
 *
 * @param file the file to check
 * @return the .git folder if found or <code>null</code> the give path cannot be resolved to a file or it's not under control of a git repository
 */
public static File resolveGitDir(File file) {
	File dot = new File(file, Constants.DOT_GIT);
	if (RepositoryCache.FileKey.isGitRepository(dot, FS.DETECTED)) {
		return dot;
	} else if (dot.isFile()) {
		try {
			return getSymRef(file, dot, FS.DETECTED);
		} catch (IOException ignored) {
			// Continue searching if gitdir ref isn't found
		}
	} else if (RepositoryCache.FileKey.isGitRepository(file, FS.DETECTED)) {
		return file;
	}
	return null;
}
 
Example #12
Source File: JGitHelper.java    From go-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public void submoduleRemove(String folderName) {
    configRemoveSection(folderName);

    Repository repository = null;
    try {
        repository = getRepository(workingDir);

        StoredConfig gitSubmodulesConfig = new FileBasedConfig(null, new File(repository.getWorkTree(), Constants.DOT_GIT_MODULES), FS.DETECTED);
        gitSubmodulesConfig.unsetSection(ConfigConstants.CONFIG_SUBMODULE_SECTION, folderName);
        gitSubmodulesConfig.save();

        Git git = Git.wrap(repository);
        git.rm().setCached(true).addFilepattern(folderName).call();

        FileUtils.deleteQuietly(new File(workingDir, folderName));
    } catch (Exception e) {
        throw new RuntimeException("sub-module remove failed", e);
    } finally {
        if (repository != null) {
            repository.close();
        }
    }
}
 
Example #13
Source File: ConfigOption.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Retrieves local config without any base config.
 */
private FileBasedConfig getLocalConfig() throws IOException {
	// TODO: remove usage of internal type
	if (db instanceof FileRepository) {
		FileRepository fr = (FileRepository) db;
		FileBasedConfig config = new FileBasedConfig(fr.getConfig().getFile(), FS.detect());
		try {
			config.load();
		} catch (ConfigInvalidException e) {
			throw new IOException(e);
		}
		return config;
	} else {
		throw new IllegalArgumentException("Repository is not file based.");
	}
}
 
Example #14
Source File: GitCloneTest.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testCloneOverSshWithPassword() throws Exception {
	Assume.assumeTrue(sshRepo != null);
	Assume.assumeTrue(password != null);
	Assume.assumeTrue(knownHosts != null);

	createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
	JSONObject project = createProjectOrLink(workspaceLocation, getMethodName().concat("Project"), null);
	String workspaceId = workspaceIdFromLocation(workspaceLocation);
	IPath clonePath = getClonePath(workspaceId, project);
	URIish uri = new URIish(sshRepo);
	WebRequest request = new PostGitCloneRequest().setURIish(uri).setFilePath(clonePath).setKnownHosts(knownHosts).setPassword(password).getWebRequest();
	String contentLocation = clone(request);
	File file = getRepositoryForContentLocation(contentLocation).getDirectory().getParentFile();
	assertTrue(file.exists());
	assertTrue(file.isDirectory());
	assertTrue(RepositoryCache.FileKey.isGitRepository(new File(file, Constants.DOT_GIT), FS.DETECTED));
}
 
Example #15
Source File: GitCloneTest.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testCloneOverSshWithPassphraseProtectedKey() throws Exception {
	Assume.assumeTrue(sshRepo2 != null);
	Assume.assumeTrue(privateKey != null);
	Assume.assumeTrue(passphrase != null);

	createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
	String workspaceId = workspaceIdFromLocation(workspaceLocation);
	JSONObject project = createProjectOrLink(workspaceLocation, getMethodName().concat("Project"), null);
	IPath clonePath = getClonePath(workspaceId, project);
	URIish uri = new URIish(sshRepo2);
	WebRequest request = new PostGitCloneRequest().setURIish(uri).setFilePath(clonePath).setKnownHosts(knownHosts2).setPrivateKey(privateKey).setPublicKey(publicKey).setPassphrase(passphrase).getWebRequest();
	String contentLocation = clone(request);

	File file = getRepositoryForContentLocation(contentLocation).getDirectory().getParentFile();
	assertTrue(file.exists());
	assertTrue(file.isDirectory());
	assertTrue(RepositoryCache.FileKey.isGitRepository(new File(file, Constants.DOT_GIT), FS.DETECTED));
}
 
Example #16
Source File: AgentProxyAwareJschConfigSessionFactory.java    From gitflow-incremental-builder with MIT License 6 votes vote down vote up
@Override
protected Session createSession(Host hc, String user, String host, int port, FS fs)
        throws JSchException {
    JSch jSch = getJSch(hc, fs);

    // assumption: identities from agent are always unencrypted
    final Collection<Identity> allUnencryptedIdentities = getIdentitiesFromAgentProxy();

    @SuppressWarnings("unchecked")
    Collection<Identity> identities = ((Collection<Identity>) jSch.getIdentityRepository().getIdentities());
    identities.stream()
            .filter(id -> !id.isEncrypted())
            .forEach(allUnencryptedIdentities::add);
    
    Session session = jSch.getSession(user, host, port);
    session.setIdentityRepository(new ReadOnlyIdentityRepository(allUnencryptedIdentities));
    return session;
}
 
Example #17
Source File: HttpDelegatingCredentialsProvider.java    From gitflow-incremental-builder with MIT License 6 votes vote down vote up
private CredentialsPair lookupCredentials(URIish uri) throws IOException, InterruptedException {
    // utilize JGit command execution capabilities
    FS fs = FS.detect();
    ProcessBuilder procBuilder = fs.runInShell("git", new String[] {"credential", "fill"});

    // prevent native git from requesting console input (not implemented)
    procBuilder.environment().put("GIT_TERMINAL_PROMPT", "0");

    // add additional environment entries, if present (test only)
    if (!additionalNativeGitEnvironment.isEmpty()) {
        procBuilder.environment().putAll(additionalNativeGitEnvironment);
    }
    procBuilder.directory(projectDir.toFile());

    ExecutionResult result = fs.execute(procBuilder, new ByteArrayInputStream(buildGitCommandInput(uri).getBytes(Charset.defaultCharset())));
    if (result.getRc() != 0) {
        logger.info(bufferToString(result.getStdout()));
        logger.error(bufferToString(result.getStderr()));
        throw new IllegalStateException("Native Git invocation failed with return code " + result.getRc()
                + ". See previous log output for more details.");
    }

    return extractCredentials(bufferToString(result.getStdout()));
}
 
Example #18
Source File: GitUtils.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
private static File getSymRef(File workTree, File dotGit, FS fs)
		throws IOException {
	byte[] content = IO.readFully(dotGit);
	if (!isSymRef(content))
		throw new IOException(MessageFormat.format(
				JGitText.get().invalidGitdirRef, dotGit.getAbsolutePath()));

	int pathStart = 8;
	int lineEnd = RawParseUtils.nextLF(content, pathStart);
	if (content[lineEnd - 1] == '\n')
		lineEnd--;
	if (lineEnd == pathStart)
		throw new IOException(MessageFormat.format(
				JGitText.get().invalidGitdirRef, dotGit.getAbsolutePath()));

	String gitdirPath = RawParseUtils.decode(content, pathStart, lineEnd);
	File gitdirFile = fs.resolve(workTree, gitdirPath);
	if (gitdirFile.isAbsolute())
		return gitdirFile;
	else
		return new File(workTree, gitdirPath).getCanonicalFile();
}
 
Example #19
Source File: SystemInfo.java    From app-runner with MIT License 6 votes vote down vote up
private static List<String> getPublicKeys() throws Exception {
    return new JschConfigSessionFactory() {
        @Override
        protected void configure(OpenSshConfig.Host hc, Session session) {
        }
        List<String> getPublicKeys() throws Exception {
            JSch jSch = createDefaultJSch(FS.DETECTED);
            List<String> keys = new ArrayList<>();
            for (Object o : jSch.getIdentityRepository().getIdentities()) {
                Identity i = (Identity) o;
                KeyPair keyPair = KeyPair.load(jSch, i.getName(), null);
                StringBuilder sb = new StringBuilder();
                try (StringBuilderWriter sbw = new StringBuilderWriter(sb);
                     OutputStream os = new WriterOutputStream(sbw, "UTF-8")) {
                    keyPair.writePublicKey(os, keyPair.getPublicKeyComment());
                } finally {
                    keyPair.dispose();
                }
                keys.add(sb.toString().trim());
            }
            return keys;
        }
    }.getPublicKeys();
}
 
Example #20
Source File: GitRepositoryHelper.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
public SshSessionFactory getSshSessionFactory(String privateKey, final Path tempKey)  {
    try {
        Files.write(tempKey, privateKey.getBytes());
        SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
            @Override
            protected void configure(OpenSshConfig.Host hc, Session session) {
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
            }

            @Override
            protected JSch createDefaultJSch(FS fs) throws JSchException {
                JSch defaultJSch = new JSch();
                defaultJSch.addIdentity(tempKey.toAbsolutePath().toString());
                return defaultJSch;
            }
        };
        return sshSessionFactory;
    } catch (IOException e) {
        logger.error("Failed to create private key for SSH connection.", e);
    }
    return null;
}
 
Example #21
Source File: GitConfigMonitorTest.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void setup() throws Exception {
  cleanUpDir(TEST_DIR);

  // Create a bare repository
  RepositoryCache.FileKey fileKey = RepositoryCache.FileKey.exact(remoteDir, FS.DETECTED);
  this.remoteRepo = fileKey.open(false);
  this.remoteRepo.create(true);

  this.gitForPush = Git.cloneRepository().setURI(this.remoteRepo.getDirectory().getAbsolutePath()).setDirectory(cloneDir).call();

  // push an empty commit as a base for detecting changes
  this.gitForPush.commit().setMessage("First commit").call();
  this.gitForPush.push().setRemote("origin").setRefSpecs(this.masterRefSpec).call();

  this.config = ConfigBuilder.create()
      .addPrimitive(GitConfigMonitor.GIT_CONFIG_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_REPO_URI,
          this.remoteRepo.getDirectory().getAbsolutePath())
      .addPrimitive(GitConfigMonitor.GIT_CONFIG_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_REPO_DIR, TEST_DIR + "/jobConfig")
      .addPrimitive(FlowCatalog.FLOWSPEC_STORE_DIR_KEY, TEST_DIR + "flowCatalog")
      .addPrimitive(ConfigurationKeys.GIT_MONITOR_POLLING_INTERVAL, 5)
      .build();

  this.flowCatalog = new FlowCatalog(config);
  this.flowCatalog.startAsync().awaitRunning();
  this.gitConfigMonitor = new GitConfigMonitor(this.config, this.flowCatalog);
  this.gitConfigMonitor.setActive(true);
}
 
Example #22
Source File: NoGitignoreIterator.java    From writelatex-git-bridge with MIT License 5 votes vote down vote up
public NoGitignoreIterator(
        File root,
        FS fs,
        WorkingTreeOptions options,
        FileModeStrategy fileModeStrategy
) {
    super(root, fs, options, fileModeStrategy);
}
 
Example #23
Source File: BaseDifferentFilesTest.java    From gitflow-incremental-builder with MIT License 5 votes vote down vote up
@Override
@BeforeEach
protected void before(TestInfo testInfo) throws Exception {
    jGitUserHomeBackup = FS.DETECTED.userHome();
    super.before(testInfo);
    userHome = Files.createDirectory(tempDir.resolve("userHome"));
    FS.DETECTED.setUserHome(userHome.toFile());
}
 
Example #24
Source File: GitMonitoringService.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private SshSessionFactory getSshSessionFactory() {
  JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() {
    @Override
    protected void configure(OpenSshConfig.Host hc, Session session) {
      if (!GitMonitoringService.this.strictHostKeyCheckingEnabled) {
        session.setConfig("StrictHostKeyChecking", "no");
      }
    }

    @Override
    protected JSch createDefaultJSch(FS fs) throws JSchException {
      if (GitMonitoringService.this.isJschLoggerEnabled) {
        JSch.setLogger(new JschLogger());
      }
      JSch defaultJSch = super.createDefaultJSch(fs);
      defaultJSch.getIdentityRepository().removeAll();
      if (GitMonitoringService.this.privateKeyPath != null) {
        defaultJSch.addIdentity(GitMonitoringService.this.privateKeyPath, GitMonitoringService.this.passphrase);
      } else {
        defaultJSch.addIdentity("gaas-git", GitMonitoringService.this.privateKey, null,
            GitMonitoringService.this.passphrase.getBytes(Charset.forName("UTF-8")));
      }
      if (!Strings.isNullOrEmpty(GitMonitoringService.this.knownHosts)) {
        defaultJSch.setKnownHosts(new ByteArrayInputStream(GitMonitoringService.this.knownHosts.getBytes(Charset.forName("UTF-8"))));
      } else if (!Strings.isNullOrEmpty(GitMonitoringService.this.knownHostsFile)) {
        defaultJSch.setKnownHosts(GitMonitoringService.this.knownHostsFile);
      }
      return defaultJSch;
    }
  };
  return sessionFactory;
}
 
Example #25
Source File: TransportConfigurationIntegrationTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void strictHostKeyCheckShouldCheck() throws Exception {
	String uri = "git+ssh://git@somegitserver/somegitrepo";
	SshSessionFactory.setInstance(null);
	this.jGitEnvironmentRepository.setUri(uri);
	this.jGitEnvironmentRepository.setBasedir(new File("./mybasedir"));
	assertThat(this.jGitEnvironmentRepository.isStrictHostKeyChecking())
			.isTrue();
	this.jGitEnvironmentRepository.setCloneOnStart(true);
	try {
		// this will throw but we don't care about connecting.
		this.jGitEnvironmentRepository.afterPropertiesSet();
	}
	catch (Exception e) {
		final OpenSshConfig.Host hc = OpenSshConfig.get(FS.detect())
				.lookup("github.com");
		JschConfigSessionFactory factory = (JschConfigSessionFactory) SshSessionFactory
				.getInstance();
		// There's no public method that can be used to inspect the ssh
		// configuration, so we'll reflect
		// the configure method to allow us to check that the config
		// property is set as expected.
		Method configure = factory.getClass().getDeclaredMethod("configure",
				OpenSshConfig.Host.class, Session.class);
		configure.setAccessible(true);
		Session session = mock(Session.class);
		ArgumentCaptor<String> keyCaptor = ArgumentCaptor
				.forClass(String.class);
		ArgumentCaptor<String> valueCaptor = ArgumentCaptor
				.forClass(String.class);
		configure.invoke(factory, hc, session);
		verify(session).setConfig(keyCaptor.capture(), valueCaptor.capture());
		configure.setAccessible(false);
		assertThat("yes".equals(valueCaptor.getValue())).isTrue();
	}
}
 
Example #26
Source File: UpdaterGenerator.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Davide you might notice that I have made functions smaller.
 * It makes code immensely more readable and you quickly are able
 * to resume the code from where you left.
 * Understanding takes lesser time, as number of lines are lesser.
 * @return 
 */
private boolean init_CheckDir_gitClone(){
    //Check if the given directory exists
    boolean gitUpdated = true;
    if (RepositoryCache.FileKey.isGitRepository(new File(gitDirectory.getAbsolutePath(), ".git"), FS.DETECTED)) {
        // Already cloned. Just need to pull a repository here.
        System.out.println("git pull");
        gitUpdated = gitPull(gitDirectory);
    } else {
        // Not present or not a Git repository.
        System.out.println("git clone");
        gitClone(gitDirectory);
    }return gitUpdated;
}
 
Example #27
Source File: SecureShellAuthentication.java    From github-bucket with ISC License 5 votes vote down vote up
public SecureShellAuthentication(Bucket bucket, AmazonS3 client) {
    factory = new JschConfigSessionFactory() {

        @Override
        public synchronized RemoteSession getSession(URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException {
            // Do not check for default ssh user config
            fs.setUserHome(null);
            return super.getSession(uri, credentialsProvider, fs, tms);
        }

        @Override
        protected void configure(OpenSshConfig.Host host, Session session) {
            session.setConfig("HashKnownHosts", "no");
            if ("localhost".equalsIgnoreCase(host.getHostName())) {
                session.setConfig("StrictHostKeyChecking", "no");
            }
        }

        @Override
        protected void configureJSch(JSch jsch) {
            S3Object file;
            file = client.getObject(bucket.getName(), ".ssh/known_hosts");
            try (InputStream is = file.getObjectContent()) {
                jsch.setKnownHosts(is);
            } catch (IOException | JSchException e) {
                throw new IllegalArgumentException("Missing known hosts file on s3: .ssh/known_hosts", e);
            }
            file = client.getObject(bucket.getName(), ".ssh/id_rsa");
            try (InputStream is = file.getObjectContent()) {
                jsch.addIdentity("git", IOUtils.toByteArray(is), null, new byte[0]);
            } catch (IOException | JSchException e) {
                throw new IllegalArgumentException("Missing key file on s3: .ssh/id_rsa", e);
            }
        }
    };
}
 
Example #28
Source File: NoGitignoreIterator.java    From writelatex-git-bridge with MIT License 5 votes vote down vote up
protected NoGitignoreIterator(
        WorkingTreeIterator p,
        File root,
        FS fs,
        FileModeStrategy fileModeStrategy
) {
    super(p, root, fs, fileModeStrategy);
}
 
Example #29
Source File: ConfigServerTestUtils.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
public static Repository prepareBareRemote() throws IOException {
	// Create a folder in the temp folder that will act as the remote repository
	File remoteDir = File.createTempFile("remote", "");
	remoteDir.delete();
	remoteDir.mkdirs();

	// Create a bare repository
	FileKey fileKey = FileKey.exact(remoteDir, FS.DETECTED);
	Repository remoteRepo = fileKey.open(false);
	remoteRepo.create(true);

	return remoteRepo;
}
 
Example #30
Source File: TransportConfigurationIntegrationTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void strictHostKeyCheckShouldCheck() throws Exception {
	String uri = "git+ssh://git@somegitserver/somegitrepo";
	SshSessionFactory.setInstance(null);
	this.jGitEnvironmentRepository.setUri(uri);
	this.jGitEnvironmentRepository.setBasedir(new File("./mybasedir"));
	assertThat(this.jGitEnvironmentRepository.isStrictHostKeyChecking())
			.isTrue();
	this.jGitEnvironmentRepository.setCloneOnStart(true);
	try {
		// this will throw but we don't care about connecting.
		this.jGitEnvironmentRepository.afterPropertiesSet();
	}
	catch (Exception e) {
		final OpenSshConfig.Host hc = OpenSshConfig.get(FS.detect())
				.lookup("github.com");
		JschConfigSessionFactory factory = (JschConfigSessionFactory) SshSessionFactory
				.getInstance();
		// There's no public method that can be used to inspect the ssh
		// configuration, so we'll reflect
		// the configure method to allow us to check that the config
		// property is set as expected.
		Method configure = factory.getClass().getDeclaredMethod("configure",
				OpenSshConfig.Host.class, Session.class);
		configure.setAccessible(true);
		Session session = mock(Session.class);
		ArgumentCaptor<String> keyCaptor = ArgumentCaptor
				.forClass(String.class);
		ArgumentCaptor<String> valueCaptor = ArgumentCaptor
				.forClass(String.class);
		configure.invoke(factory, hc, session);
		verify(session).setConfig(keyCaptor.capture(), valueCaptor.capture());
		configure.setAccessible(false);
		assertThat("yes".equals(valueCaptor.getValue())).isTrue();
	}
}