Search in sources :

Example 1 with BasicSSHUserPrivateKey

use of com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey in project blueocean-plugin by jenkinsci.

the class GitCacheCloneReadSaveRequest method getActiveRepository.

@Nonnull
private Git getActiveRepository(Repository repository) throws IOException {
    try {
        // Clone the bare repository
        File cloneDir = File.createTempFile("clone", "");
        if (cloneDir.exists()) {
            if (cloneDir.isDirectory()) {
                FileUtils.deleteDirectory(cloneDir);
            } else {
                if (!cloneDir.delete()) {
                    throw new ServiceException.UnexpectedErrorException("Unable to delete repository clone");
                }
            }
        }
        if (!cloneDir.mkdirs()) {
            throw new ServiceException.UnexpectedErrorException("Unable to create repository clone directory");
        }
        String url = repository.getConfig().getString("remote", "origin", "url");
        Git gitClient = Git.cloneRepository().setCloneAllBranches(false).setProgressMonitor(new CloneProgressMonitor(url)).setURI(repository.getDirectory().getCanonicalPath()).setDirectory(cloneDir).call();
        RemoteRemoveCommand remove = gitClient.remoteRemove();
        remove.setName("origin");
        remove.call();
        RemoteAddCommand add = gitClient.remoteAdd();
        add.setName("origin");
        add.setUri(new URIish(gitSource.getRemote()));
        add.call();
        if (GitUtils.isSshUrl(gitSource.getRemote())) {
            // Get committer info and credentials
            User user = User.current();
            if (user == null) {
                throw new ServiceException.UnauthorizedException("Not authenticated");
            }
            BasicSSHUserPrivateKey privateKey = UserSSHKeyManager.getOrCreate(user);
            // Make sure up-to-date and credentials work
            GitUtils.fetch(repository, privateKey);
        } else {
            FetchCommand fetch = gitClient.fetch();
            fetch.call();
        }
        if (!StringUtils.isEmpty(sourceBranch) && !sourceBranch.equals(branch)) {
            CheckoutCommand checkout = gitClient.checkout();
            checkout.setStartPoint("origin/" + sourceBranch);
            checkout.setName(sourceBranch);
            // to create a new local branch
            checkout.setCreateBranch(true);
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();
            checkout = gitClient.checkout();
            checkout.setName(branch);
            // this *should* be a new branch
            checkout.setCreateBranch(true);
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();
        } else {
            CheckoutCommand checkout = gitClient.checkout();
            checkout.setStartPoint("origin/" + branch);
            checkout.setName(branch);
            // to create a new local branch
            checkout.setCreateBranch(true);
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();
        }
        return gitClient;
    } catch (GitAPIException | URISyntaxException ex) {
        throw new ServiceException.UnexpectedErrorException("Unable to get working repository directory", ex);
    }
}
Also used : URIish(org.eclipse.jgit.transport.URIish) CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) User(hudson.model.User) RemoteRemoveCommand(org.eclipse.jgit.api.RemoteRemoveCommand) RemoteAddCommand(org.eclipse.jgit.api.RemoteAddCommand) URISyntaxException(java.net.URISyntaxException) BasicSSHUserPrivateKey(com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.eclipse.jgit.api.Git) ServiceException(io.jenkins.blueocean.commons.ServiceException) FetchCommand(org.eclipse.jgit.api.FetchCommand) File(java.io.File) Nonnull(javax.annotation.Nonnull)

Example 2 with BasicSSHUserPrivateKey

use of com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey in project blueocean-plugin by jenkinsci.

the class UserSSHKeyManager method reset.

/**
 * Resets the user's generated key by deleting it and creating a new one
 * @param user user to reset a key for
 */
public static void reset(@Nonnull User user) {
    Preconditions.checkNotNull(user);
    try {
        // create one!
        CredentialsStore store = getUserStore(user);
        if (store == null) {
            throw new ServiceException.ForbiddenException(String.format("Logged in user: %s doesn't have writable credentials store", user.getId()));
        }
        Credentials key = null;
        // try to find the key
        for (Credentials cred : store.getCredentials(getDomain(store))) {
            if (cred instanceof BasicSSHUserPrivateKey) {
                BasicSSHUserPrivateKey sshKey = (BasicSSHUserPrivateKey) cred;
                if (BLUEOCEAN_GENERATED_SSH_KEY_ID.equals(sshKey.getId())) {
                    key = sshKey;
                    break;
                }
            }
        }
        if (key != null) {
            store.removeCredentials(getDomain(store), key);
            store.save();
        }
    } catch (IOException ex) {
        throw new ServiceException.UnexpectedErrorException("Unable to reset the user's key", ex);
    }
}
Also used : ServiceException(io.jenkins.blueocean.commons.ServiceException) CredentialsStore(com.cloudbees.plugins.credentials.CredentialsStore) IOException(java.io.IOException) Credentials(com.cloudbees.plugins.credentials.Credentials) BasicSSHUserPrivateKey(com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey)

Example 3 with BasicSSHUserPrivateKey

use of com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey in project blueocean-plugin by jenkinsci.

the class GitReadSaveTest method startSSH.

private void startSSH(@Nullable User u) throws Exception {
    if (sshd == null) {
        // Set up an SSH server with access to a git repo
        User user;
        if (u == null) {
            user = login();
        } else {
            user = u;
        }
        final BasicSSHUserPrivateKey key = UserSSHKeyManager.getOrCreate(user);
        final JSch jsch = new JSch();
        final KeyPair pair = KeyPair.load(jsch, key.getPrivateKey().getBytes(), null);
        File keyFile = new File(System.getProperty("TEST_SSH_SERVER_KEY_FILE", File.createTempFile("hostkey", "ser").getCanonicalPath()));
        int port = Integer.parseInt(System.getProperty("TEST_SSH_SERVER_PORT", "0"));
        boolean allowLocalUser = Boolean.getBoolean("TEST_SSH_SERVER_ALLOW_LOCAL");
        String userPublicKey = Base64.encode(pair.getPublicKeyBlob());
        sshd = new SSHServer(repoForSSH.getRoot(), keyFile, port, allowLocalUser, ImmutableMap.of("bob", userPublicKey), true);
        // Go, go, go
        sshd.start();
    }
}
Also used : KeyPair(com.jcraft.jsch.KeyPair) SSHServer(io.jenkins.blueocean.test.ssh.SSHServer) User(hudson.model.User) JSch(com.jcraft.jsch.JSch) File(java.io.File) BasicSSHUserPrivateKey(com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey)

Example 4 with BasicSSHUserPrivateKey

use of com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey in project blueocean-plugin by jenkinsci.

the class UserSSHKeyManager method getOrCreate.

/**
 * Gets the existing generated SSH key for the user or creates one and
 * returns it in the user's credential store
 * @param user owner of the key
 * @return the user's personal private key
 */
@Nonnull
public static BasicSSHUserPrivateKey getOrCreate(@Nonnull User user) {
    Preconditions.checkNotNull(user);
    CredentialsStore store = getUserStore(user);
    if (store == null) {
        throw new ServiceException.ForbiddenException(String.format("Logged in user: %s doesn't have writable credentials store", user.getId()));
    }
    // try to find the right key
    for (Credentials cred : store.getCredentials(getDomain(store))) {
        if (cred instanceof BasicSSHUserPrivateKey) {
            BasicSSHUserPrivateKey sshKey = (BasicSSHUserPrivateKey) cred;
            if (BLUEOCEAN_GENERATED_SSH_KEY_ID.equals(sshKey.getId())) {
                return sshKey;
            }
        }
    }
    // if none found, create one
    try {
        // create one!
        String privateKey = SSHKeyUtils.generateKey(KEY_SIZE).trim();
        BasicSSHUserPrivateKey.DirectEntryPrivateKeySource keySource = new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(privateKey);
        BasicSSHUserPrivateKey key = new BasicSSHUserPrivateKey(CredentialsScope.USER, BLUEOCEAN_GENERATED_SSH_KEY_ID, user.getId(), keySource, null, BLUEOCEAN_GENERATED_SSH_KEY_ID);
        store.addCredentials(getDomain(store), key);
        store.save();
        return key;
    } catch (IOException ex) {
        throw new ServiceException.UnexpectedErrorException("Failed to create the private key", ex);
    }
}
Also used : ServiceException(io.jenkins.blueocean.commons.ServiceException) CredentialsStore(com.cloudbees.plugins.credentials.CredentialsStore) IOException(java.io.IOException) Credentials(com.cloudbees.plugins.credentials.Credentials) BasicSSHUserPrivateKey(com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey) Nonnull(javax.annotation.Nonnull)

Aggregations

BasicSSHUserPrivateKey (com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey)4 ServiceException (io.jenkins.blueocean.commons.ServiceException)3 Credentials (com.cloudbees.plugins.credentials.Credentials)2 CredentialsStore (com.cloudbees.plugins.credentials.CredentialsStore)2 User (hudson.model.User)2 File (java.io.File)2 IOException (java.io.IOException)2 Nonnull (javax.annotation.Nonnull)2 JSch (com.jcraft.jsch.JSch)1 KeyPair (com.jcraft.jsch.KeyPair)1 SSHServer (io.jenkins.blueocean.test.ssh.SSHServer)1 URISyntaxException (java.net.URISyntaxException)1 CheckoutCommand (org.eclipse.jgit.api.CheckoutCommand)1 FetchCommand (org.eclipse.jgit.api.FetchCommand)1 Git (org.eclipse.jgit.api.Git)1 RemoteAddCommand (org.eclipse.jgit.api.RemoteAddCommand)1 RemoteRemoveCommand (org.eclipse.jgit.api.RemoteRemoveCommand)1 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)1 URIish (org.eclipse.jgit.transport.URIish)1