Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support of BasicAuthentication Authentication to Git #1940

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
*******************************************************************************/
package org.eclipse.che.api.git.shared;

import org.eclipse.che.commons.annotation.Nullable;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
Expand All @@ -28,19 +29,26 @@ public class ProviderInfo {

private Map<String, String> info = new HashMap<>();

public ProviderInfo(@NotNull String providerName) {
info.put(PROVIDER_NAME, providerName);
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also please fix java doc of getAuthenticateUrl method and describe that it can return null value and add org.eclipse.che.commons.annotation.Nullable for it

public ProviderInfo(@NotNull String providerName,
@NotNull String authenticateUrl) {
info.put(PROVIDER_NAME, providerName);
info.put(AUTHENTICATE_URL, authenticateUrl);
}


public String getProviderName() {
return info.get(PROVIDER_NAME);
}

public String getAuthenticateUrl() {
return info.get(AUTHENTICATE_URL);
}
/**
* @return authenticate URL. It retrun String or null value.
*/
@Nullable
public String getAuthenticateUrl() { return info.get(AUTHENTICATE_URL); }

public void put(String key, String value) {
info.put(key, value);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.git;

import com.google.inject.Singleton;
import org.eclipse.che.api.git.shared.ProviderInfo;

/**
* Credentials provider for Git basic authentication
*
* @author Yossi Balan
*/
@Singleton
public class GitBasicAuthenticationCredentialsProvider implements CredentialsProvider {

private static ThreadLocal<UserCredential> currRequestCredentials = new ThreadLocal<>();
private static final String BASIC_PROVIDER_NAME = "basic";

@Override
public UserCredential getUserCredential() {
return currRequestCredentials.get();
}

@Override
public String getId() {
return BASIC_PROVIDER_NAME;
}

@Override
public boolean canProvideCredentials(String url) {
return getUserCredential() != null;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we provide credentials for all urls? Even ssh?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sleshchenko - only http or https

}

@Override
public ProviderInfo getProviderInfo() {
return new ProviderInfo(BASIC_PROVIDER_NAME);
}

public static void setCurrentCredentials(String user, String password) {
UserCredential creds = new UserCredential(user, password, BASIC_PROVIDER_NAME);
currRequestCredentials.set(creds);
}

public static void clearCredentials() {
currRequestCredentials.set(null);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@
import static org.eclipse.che.api.core.ErrorCodes.FAILED_CHECKOUT;
import static org.eclipse.che.api.core.ErrorCodes.FAILED_CHECKOUT_WITH_START_POINT;
import static org.eclipse.che.api.git.shared.BranchListRequest.LIST_ALL;
import static org.eclipse.che.api.git.GitBasicAuthenticationCredentialsProvider.clearCredentials;
import static org.eclipse.che.api.git.GitBasicAuthenticationCredentialsProvider.setCurrentCredentials;

/**
* @author Vladyslav Zhukovskii
Expand Down Expand Up @@ -105,6 +107,7 @@ public void importSources(FolderEntry baseFolder,
IOException,
ServerException {
GitConnection git = null;
boolean credentialsHaveBeenSet = false;
try {
// For factory: checkout particular commit after clone
String commitId = null;
Expand Down Expand Up @@ -137,6 +140,12 @@ public void importSources(FolderEntry baseFolder,
recursiveEnabled = true;
}
branchMerge = parameters.get("branchMerge");
final String user = parameters.get("userName");
final String pass = parameters.get("password");
if (user != null && pass != null) {
credentialsHaveBeenSet = true;
setCurrentCredentials(user, pass);
}
}
// Get path to local file. Git works with local filesystem only.
final String localPath = baseFolder.getVirtualFile().toIoFile().getAbsolutePath();
Expand Down Expand Up @@ -197,6 +206,9 @@ public void importSources(FolderEntry baseFolder,
if (git != null) {
git.close();
}
if (credentialsHaveBeenSet) {
clearCredentials();
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
import org.eclipse.che.api.git.shared.TagCreateRequest;
import org.eclipse.che.api.git.shared.TagDeleteRequest;
import org.eclipse.che.api.git.shared.TagListRequest;
import org.eclipse.che.api.git.shared.GitRequest;
import org.eclipse.che.plugin.ssh.key.script.SshKeyProvider;
import org.eclipse.che.commons.proxy.ProxyAuthenticator;
import org.eclipse.jgit.api.AddCommand;
Expand Down Expand Up @@ -515,7 +516,7 @@ protected void onEndTask(String taskName, int workCurr, int workTotal, int perce
}
});

executeRemoteCommand(remoteUri, cloneCommand);
executeRemoteCommand(remoteUri, cloneCommand , request);

StoredConfig repositoryConfig = getRepository().getConfig();
GitUser gitUser = getUser();
Expand Down Expand Up @@ -696,7 +697,7 @@ public void fetch(FetchRequest request) throws GitException, UnauthorizedExcepti
}
fetchCommand.setRemoveDeletedRefs(request.isRemoveDeletedRefs());

executeRemoteCommand(remoteUri, fetchCommand);
executeRemoteCommand(remoteUri, fetchCommand, request);
} catch (GitException | GitAPIException exception) {
String errorMessage;
if (exception.getMessage().contains("Invalid remote: ")) {
Expand Down Expand Up @@ -1013,7 +1014,7 @@ public PullResponse pull(PullRequest request) throws GitException, UnauthorizedE
fetchCommand.setTimeout(timeout);
}

FetchResult fetchResult = (FetchResult)executeRemoteCommand(remoteUri, fetchCommand);
FetchResult fetchResult = (FetchResult)executeRemoteCommand(remoteUri, fetchCommand, request);

Ref remoteBranchRef = fetchResult.getAdvertisedRef(remoteBranch);
if (remoteBranchRef == null) {
Expand Down Expand Up @@ -1081,7 +1082,7 @@ public PushResponse push(PushRequest request) throws GitException, UnauthorizedE
}
try {
@SuppressWarnings("unchecked")
Iterable<PushResult> pushResults = (Iterable<PushResult>)executeRemoteCommand(remoteUri, pushCommand);
Iterable<PushResult> pushResults = (Iterable<PushResult>)executeRemoteCommand(remoteUri, pushCommand, request);
PushResult pushResult = pushResults.iterator().next();
String commandOutput = pushResult.getMessages().isEmpty() ? "Successfully pushed to " + remoteUri : pushResult.getMessages();
Collection<RemoteRefUpdate> refUpdates = pushResult.getRemoteUpdates();
Expand Down Expand Up @@ -1589,10 +1590,11 @@ public boolean accept(File dir) {
* @throws UnauthorizedException
*/
@VisibleForTesting
Object executeRemoteCommand(String remoteUrl, TransportCommand command)
Object executeRemoteCommand(String remoteUrl, TransportCommand command, GitRequest request)
throws GitException, GitAPIException, UnauthorizedException {
File keyDirectory = null;
UserCredential credentials = null;

try {
if (GitUrlUtils.isSSH(remoteUrl)) {
keyDirectory = Files.createTempDir();
Expand Down Expand Up @@ -1622,14 +1624,19 @@ protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException
String password = remoteUrl.substring(remoteUrl.lastIndexOf(":") + 1, remoteUrl.indexOf("@"));
command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
} else {
credentials = credentialsLoader.getUserCredential(remoteUrl);
if (credentials != null) {
command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(credentials.getUserName(),
credentials.getPassword()));
String gitUser = request.getAttributes().get("username");
String gitPassword = request.getAttributes().get("password");
Copy link
Contributor

@vinokurig vinokurig Aug 15, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if (gitUser != null && gitPassword != null) {
command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(gitUser, gitPassword));
} 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) {
Expand All @@ -1656,7 +1663,6 @@ protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException
throw new GitException("Can't remove SSH key directory", exception);
}
}

ProxyAuthenticator.resetAuthenticator();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

import org.eclipse.che.api.git.CredentialsLoader;
import org.eclipse.che.api.git.GitUserResolver;
import org.eclipse.che.api.git.shared.GitRequest;
import org.eclipse.che.plugin.ssh.key.script.SshKeyProvider;
import org.eclipse.jgit.api.TransportCommand;
import org.eclipse.jgit.lib.Repository;
Expand Down Expand Up @@ -50,7 +51,8 @@ public class JGitConnectionTest {
private GitUserResolver gitUserResolver;
@Mock
private TransportCommand transportCommand;

@Mock
private GitRequest request;
@InjectMocks
private JGitConnection jGitConnection;

Expand Down Expand Up @@ -80,7 +82,7 @@ public void shouldExecuteRemoteCommandByHttpOrHttpsUrlWithCredentials(String url
passwordField.setAccessible(true);

//when
jGitConnection.executeRemoteCommand(url, transportCommand);
jGitConnection.executeRemoteCommand(url, transportCommand, request);

//then
verify(transportCommand).setCredentialsProvider(captor.capture());
Expand All @@ -94,7 +96,7 @@ public void shouldExecuteRemoteCommandByHttpOrHttpsUrlWithCredentials(String url
@Test(dataProvider = "gitUrlsWithoutOrWrongCredentials")
public void shouldNotSetCredentialsProviderIfUrlDoesNotContainCredentials(String url) throws Exception{
//when
jGitConnection.executeRemoteCommand(url, transportCommand);
jGitConnection.executeRemoteCommand(url, transportCommand, request);

//then
verify(transportCommand, never()).setCredentialsProvider(any());
Expand Down