Search in sources :

Example 1 with TransportException

use of org.eclipse.jgit.api.errors.TransportException in project gerrit by GerritCodeReview.

the class AccountIT method fetchUserBranch.

@Test
@Sandboxed
public void fetchUserBranch() throws Exception {
    setApiUser(user);
    TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers, user);
    String userRefName = RefNames.refsUsers(user.id);
    // remove default READ permissions
    ProjectConfig cfg = projectCache.checkedGet(allUsers).getConfig();
    cfg.getAccessSection(RefNames.REFS_USERS + "${" + RefPattern.USERID_SHARDED + "}", true).remove(new Permission(Permission.READ));
    saveProjectConfig(allUsers, cfg);
    // deny READ permission that is inherited from All-Projects
    deny(allUsers, RefNames.REFS + "*", Permission.READ, ANONYMOUS_USERS);
    // fetching user branch without READ permission fails
    try {
        fetch(allUsersRepo, userRefName + ":userRef");
        Assert.fail("user branch is visible although no READ permission is granted");
    } catch (TransportException e) {
    // expected because no READ granted on user branch
    }
    // allow each user to read its own user branch
    grant(allUsers, RefNames.REFS_USERS + "${" + RefPattern.USERID_SHARDED + "}", Permission.READ, false, REGISTERED_USERS);
    // fetch user branch using refs/users/YY/XXXXXXX
    fetch(allUsersRepo, userRefName + ":userRef");
    Ref userRef = allUsersRepo.getRepository().exactRef("userRef");
    assertThat(userRef).isNotNull();
    // fetch user branch using refs/users/self
    fetch(allUsersRepo, RefNames.REFS_USERS_SELF + ":userSelfRef");
    Ref userSelfRef = allUsersRepo.getRepository().getRefDatabase().exactRef("userSelfRef");
    assertThat(userSelfRef).isNotNull();
    assertThat(userSelfRef.getObjectId()).isEqualTo(userRef.getObjectId());
    accountIndexedCounter.assertNoReindex();
    // fetching user branch of another user fails
    String otherUserRefName = RefNames.refsUsers(admin.id);
    exception.expect(TransportException.class);
    exception.expectMessage("Remote does not have " + otherUserRefName + " available for fetch.");
    fetch(allUsersRepo, otherUserRefName + ":otherUserRef");
}
Also used : ProjectConfig(com.google.gerrit.server.git.ProjectConfig) GitUtil.deleteRef(com.google.gerrit.acceptance.GitUtil.deleteRef) Ref(org.eclipse.jgit.lib.Ref) InMemoryRepository(org.eclipse.jgit.internal.storage.dfs.InMemoryRepository) Permission(com.google.gerrit.common.data.Permission) PublicKeyStore.keyToString(com.google.gerrit.gpg.PublicKeyStore.keyToString) TransportException(org.eclipse.jgit.api.errors.TransportException) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test) Sandboxed(com.google.gerrit.acceptance.Sandboxed)

Example 2 with TransportException

use of org.eclipse.jgit.api.errors.TransportException in project compiler by boalang.

the class RepositoryCloner method main.

public static void main(String[] args) throws IOException, InvalidRemoteException, TransportException, GitAPIException {
    // prepare a new folder for the cloned repository
    String localpath = args[1];
    String url = args[0];
    REMOTE_URL = url;
    File localPath = new File(localpath);
    if (!localPath.exists())
        localPath.mkdir();
    // then clone
    Git result = null;
    try {
        result = Git.cloneRepository().setURI(REMOTE_URL).setDirectory(localPath).call();
        // Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks!
        // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=474093
        result.getRepository().close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (result != null && result.getRepository() != null)
            result.getRepository().close();
    }
}
Also used : Git(org.eclipse.jgit.api.Git) File(java.io.File) TransportException(org.eclipse.jgit.api.errors.TransportException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) InvalidRemoteException(org.eclipse.jgit.api.errors.InvalidRemoteException) IOException(java.io.IOException)

Example 3 with TransportException

use of org.eclipse.jgit.api.errors.TransportException in project compiler by boalang.

the class RepositoryCloner method clone.

public static void clone(String[] args) throws IOException, InvalidRemoteException, TransportException, GitAPIException {
    // prepare a new folder for the cloned repository
    String localpaths = args[1];
    String url = args[0];
    REMOTE_URL = url;
    File localPath = new File(localpaths);
    if (!localPath.exists())
        localPath.mkdir();
    // then clone
    Git result = null;
    try {
        result = Git.cloneRepository().setURI(REMOTE_URL).setDirectory(localPath).call();
        // Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks!
        // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=474093
        result.getRepository().close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (result != null && result.getRepository() != null)
            result.getRepository().close();
    }
}
Also used : Git(org.eclipse.jgit.api.Git) File(java.io.File) TransportException(org.eclipse.jgit.api.errors.TransportException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) InvalidRemoteException(org.eclipse.jgit.api.errors.InvalidRemoteException) IOException(java.io.IOException)

Example 4 with TransportException

use of org.eclipse.jgit.api.errors.TransportException in project che by eclipse.

the class JGitConnection method executeRemoteCommand.

/**
     * Execute remote jgit command.
     *
     * @param remoteUrl
     *         remote url
     * @param command
     *         command to execute
     * @return executed command
     * @throws GitException
     * @throws GitAPIException
     * @throws UnauthorizedException
     */
@VisibleForTesting
Object executeRemoteCommand(String remoteUrl, TransportCommand command, @Nullable String username, @Nullable String password) throws GitException, GitAPIException, UnauthorizedException {
    File keyDirectory = null;
    UserCredential credentials = null;
    try {
        if (GitUrlUtils.isSSH(remoteUrl)) {
            keyDirectory = Files.createTempDir();
            final File sshKey = writePrivateKeyFile(remoteUrl, keyDirectory);
            SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {

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

                @Override
                protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException {
                    JSch jsch = super.getJSch(hc, fs);
                    jsch.removeAllIdentity();
                    jsch.addIdentity(sshKey.getAbsolutePath());
                    return jsch;
                }
            };
            command.setTransportConfigCallback(transport -> {
                if (transport instanceof SshTransport) {
                    ((SshTransport) transport).setSshSessionFactory(sshSessionFactory);
                }
            });
        } else {
            if (remoteUrl != null && GIT_URL_WITH_CREDENTIALS_PATTERN.matcher(remoteUrl).matches()) {
                username = remoteUrl.substring(remoteUrl.indexOf("://") + 3, remoteUrl.lastIndexOf(":"));
                password = remoteUrl.substring(remoteUrl.lastIndexOf(":") + 1, remoteUrl.indexOf("@"));
                command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
            } else {
                if (username != null && password != null) {
                    command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
                } else {
                    credentials = credentialsLoader.getUserCredential(remoteUrl);
                    if (credentials != null) {
                        command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(credentials.getUserName(), credentials.getPassword()));
                    }
                }
            }
        }
        ProxyAuthenticator.initAuthenticator(remoteUrl);
        return command.call();
    } catch (GitException | TransportException exception) {
        if ("Unable get private ssh key".equals(exception.getMessage())) {
            throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNABLE_GET_PRIVATE_SSH_KEY);
        } else if (exception.getMessage().contains(ERROR_AUTHENTICATION_REQUIRED)) {
            final ProviderInfo info = credentialsLoader.getProviderInfo(remoteUrl);
            if (info != null) {
                throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNAUTHORIZED_GIT_OPERATION, ImmutableMap.of(PROVIDER_NAME, info.getProviderName(), AUTHENTICATE_URL, info.getAuthenticateUrl(), "authenticated", Boolean.toString(credentials != null)));
            }
            throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNAUTHORIZED_GIT_OPERATION);
        } else {
            throw exception;
        }
    } finally {
        if (keyDirectory != null && keyDirectory.exists()) {
            try {
                FileUtils.delete(keyDirectory, FileUtils.RECURSIVE);
            } catch (IOException exception) {
                throw new GitException("Can't remove SSH key directory", exception);
            }
        }
        ProxyAuthenticator.resetAuthenticator();
    }
}
Also used : UserCredential(org.eclipse.che.api.git.UserCredential) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) GitException(org.eclipse.che.api.git.exception.GitException) IOException(java.io.IOException) SshSessionFactory(org.eclipse.jgit.transport.SshSessionFactory) JSch(com.jcraft.jsch.JSch) FS(org.eclipse.jgit.util.FS) TransportException(org.eclipse.jgit.api.errors.TransportException) ProviderInfo(org.eclipse.che.api.git.shared.ProviderInfo) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) JschConfigSessionFactory(org.eclipse.jgit.transport.JschConfigSessionFactory) DiffCommitFile(org.eclipse.che.api.git.shared.DiffCommitFile) File(java.io.File) SshTransport(org.eclipse.jgit.transport.SshTransport) Session(com.jcraft.jsch.Session) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 5 with TransportException

use of org.eclipse.jgit.api.errors.TransportException in project gerrit by GerritCodeReview.

the class DiffPreferencesIT method cleanUp.

@After
public void cleanUp() throws Exception {
    gApi.accounts().id(admin.getId().toString()).setDiffPreferences(DiffPreferencesInfo.defaults());
    TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers);
    try {
        fetch(allUsersRepo, RefNames.REFS_USERS_DEFAULT + ":defaults");
    } catch (TransportException e) {
        if (e.getMessage().equals("Remote does not have " + RefNames.REFS_USERS_DEFAULT + " available for fetch.")) {
            return;
        }
        throw e;
    }
    allUsersRepo.reset("defaults");
    PushOneCommit push = pushFactory.create(db, admin.getIdent(), allUsersRepo, "Delete default preferences", VersionedAccountPreferences.PREFERENCES, "");
    push.rm(RefNames.REFS_USERS_DEFAULT).assertOkStatus();
}
Also used : InMemoryRepository(org.eclipse.jgit.internal.storage.dfs.InMemoryRepository) TransportException(org.eclipse.jgit.api.errors.TransportException) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) After(org.junit.After)

Aggregations

TransportException (org.eclipse.jgit.api.errors.TransportException)5 File (java.io.File)3 IOException (java.io.IOException)3 Git (org.eclipse.jgit.api.Git)2 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)2 InvalidRemoteException (org.eclipse.jgit.api.errors.InvalidRemoteException)2 InMemoryRepository (org.eclipse.jgit.internal.storage.dfs.InMemoryRepository)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)1 GitUtil.deleteRef (com.google.gerrit.acceptance.GitUtil.deleteRef)1 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)1 Sandboxed (com.google.gerrit.acceptance.Sandboxed)1 Permission (com.google.gerrit.common.data.Permission)1 PublicKeyStore.keyToString (com.google.gerrit.gpg.PublicKeyStore.keyToString)1 ProjectConfig (com.google.gerrit.server.git.ProjectConfig)1 JSch (com.jcraft.jsch.JSch)1 Session (com.jcraft.jsch.Session)1 UnauthorizedException (org.eclipse.che.api.core.UnauthorizedException)1 UserCredential (org.eclipse.che.api.git.UserCredential)1 GitException (org.eclipse.che.api.git.exception.GitException)1