Skip to content

Commit

Permalink
Intercept ScmComunicationException on workspace start
Browse files Browse the repository at this point in the history
  • Loading branch information
vinokurig committed Sep 2, 2024
1 parent e04d787 commit 46114a4
Show file tree
Hide file tree
Showing 25 changed files with 171 additions and 83 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ public PersonalAccessToken fetchAndSave(Subject cheUser, String scmServerUrl)

@Override
public Optional<PersonalAccessToken> get(Subject cheUser, String scmServerUrl)
throws ScmConfigurationPersistenceException {
throws ScmConfigurationPersistenceException, ScmCommunicationException {
return doGetPersonalAccessTokens(cheUser, null, scmServerUrl).stream().findFirst();
}

Expand All @@ -174,13 +174,13 @@ public PersonalAccessToken get(String scmServerUrl)
@Override
public Optional<PersonalAccessToken> get(
Subject cheUser, String oAuthProviderName, @Nullable String scmServerUrl)
throws ScmConfigurationPersistenceException {
throws ScmConfigurationPersistenceException, ScmCommunicationException {
return doGetPersonalAccessTokens(cheUser, oAuthProviderName, scmServerUrl).stream().findFirst();
}

private List<PersonalAccessToken> doGetPersonalAccessTokens(
Subject cheUser, @Nullable String oAuthProviderName, @Nullable String scmServerUrl)
throws ScmConfigurationPersistenceException {
throws ScmConfigurationPersistenceException, ScmCommunicationException {
List<PersonalAccessToken> result = new ArrayList<>();
try {
LOG.debug(
Expand Down Expand Up @@ -358,7 +358,8 @@ public void forceRefreshPersonalAccessToken(String scmServerUrl)
}

private void removePreviousTokensIfPresent(Subject subject, String scmServerUrl)
throws ScmConfigurationPersistenceException, UnsatisfiedScmPreconditionException {
throws ScmConfigurationPersistenceException, UnsatisfiedScmPreconditionException,
ScmCommunicationException {
List<PersonalAccessToken> personalAccessTokens =
doGetPersonalAccessTokens(subject, null, scmServerUrl);
for (int i = 1; i < personalAccessTokens.size(); i++) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
import org.eclipse.che.api.workspace.server.spi.InfrastructureException;
import org.eclipse.che.api.workspace.server.spi.NamespaceResolutionContext;
import org.eclipse.che.workspace.infrastructure.kubernetes.CheServerKubernetesClientFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* This {@link NamespaceConfigurator} ensures that Secret {@link
Expand All @@ -45,6 +47,8 @@ public class CredentialsSecretConfigurator implements NamespaceConfigurator {
private static final String MERGED_GIT_CREDENTIALS_SECRET_NAME =
"devworkspace-merged-git-credentials";

private static final Logger LOG = LoggerFactory.getLogger(CredentialsSecretConfigurator.class);

@Inject
public CredentialsSecretConfigurator(
CheServerKubernetesClientFactory cheServerKubernetesClientFactory,
Expand Down Expand Up @@ -79,7 +83,7 @@ public void configure(NamespaceResolutionContext namespaceResolutionContext, Str
| ScmConfigurationPersistenceException
| UnsatisfiedScmPreconditionException
| ScmUnauthorizedException e) {
throw new RuntimeException(e);
LOG.error(e.getMessage(), e);
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,15 @@
import javax.inject.Singleton;
import org.eclipse.che.api.factory.server.scm.PersonalAccessTokenFetcher;
import org.eclipse.che.api.factory.server.scm.PersonalAccessTokenManager;
import org.eclipse.che.api.factory.server.scm.exception.ScmCommunicationException;
import org.eclipse.che.api.factory.server.scm.exception.ScmConfigurationPersistenceException;
import org.eclipse.che.api.workspace.server.spi.InfrastructureException;
import org.eclipse.che.api.workspace.server.spi.NamespaceResolutionContext;
import org.eclipse.che.commons.env.EnvironmentContext;
import org.eclipse.che.commons.subject.Subject;
import org.eclipse.che.workspace.infrastructure.kubernetes.CheServerKubernetesClientFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Ensures that OAuth token that are represented by Kubernetes Secrets are valid.
Expand All @@ -44,6 +47,8 @@ public class OAuthTokenSecretsConfigurator implements NamespaceConfigurator {
"app.kubernetes.io/part-of", "che.eclipse.org",
"app.kubernetes.io/component", "scm-personal-access-token");

private static final Logger LOG = LoggerFactory.getLogger(OAuthTokenSecretsConfigurator.class);

@Inject
public OAuthTokenSecretsConfigurator(
CheServerKubernetesClientFactory cheServerKubernetesClientFactory,
Expand Down Expand Up @@ -74,8 +79,8 @@ public void configure(NamespaceResolutionContext namespaceResolutionContext, Str
Subject cheSubject = EnvironmentContext.getCurrent().getSubject();
personalAccessTokenManager.get(
cheSubject, s.getMetadata().getAnnotations().get(ANNOTATION_SCM_URL));
} catch (ScmConfigurationPersistenceException e) {
throw new RuntimeException(e);
} catch (ScmConfigurationPersistenceException | ScmCommunicationException e) {
LOG.error(e.getMessage(), e);
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
import org.eclipse.che.api.core.util.LinksHelper;
import org.eclipse.che.api.factory.server.scm.PersonalAccessToken;
import org.eclipse.che.api.factory.server.scm.PersonalAccessTokenManager;
import org.eclipse.che.api.factory.server.scm.exception.ScmCommunicationException;
import org.eclipse.che.api.factory.server.scm.exception.ScmConfigurationPersistenceException;
import org.eclipse.che.api.factory.server.scm.exception.UnsatisfiedScmPreconditionException;
import org.eclipse.che.commons.annotation.Nullable;
Expand Down Expand Up @@ -237,7 +238,7 @@ public OAuthToken getOrRefreshToken(String oauthProvider)
if (tokenOptional.isPresent()) {
return newDto(OAuthToken.class).withToken(tokenOptional.get().getToken());
}
} catch (ScmConfigurationPersistenceException e) {
} catch (ScmConfigurationPersistenceException | ScmCommunicationException e) {
throw new RuntimeException(e);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,8 @@ public Optional<Boolean> isValid(PersonalAccessToken personalAccessToken) {
}

@Override
public Optional<Pair<Boolean, String>> isValid(PersonalAccessTokenParams params) {
public Optional<Pair<Boolean, String>> isValid(PersonalAccessTokenParams params)
throws ScmCommunicationException {
if (!isValidScmServerUrl(params.getScmProviderUrl())) {
LOG.debug("not a valid url {} for current fetcher ", params.getScmProviderUrl());
return Optional.empty();
Expand All @@ -183,7 +184,7 @@ public Optional<Pair<Boolean, String>> isValid(PersonalAccessTokenParams params)
user = azureDevOpsApiClient.getUserWithPAT(params.getToken(), params.getOrganization());
}
return Optional.of(Pair.of(Boolean.TRUE, user.getEmailAddress()));
} catch (ScmItemNotFoundException | ScmCommunicationException | ScmBadRequestException e) {
} catch (ScmItemNotFoundException | ScmBadRequestException e) {
return Optional.empty();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,8 @@ public Optional<Boolean> isValid(PersonalAccessToken accessToken)
}

@Override
public Optional<Pair<Boolean, String>> isValid(PersonalAccessTokenParams params) {
public Optional<Pair<Boolean, String>> isValid(PersonalAccessTokenParams params)
throws ScmCommunicationException {
if (!bitbucketServerApiClient.isConnected(params.getScmProviderUrl())) {
// If BitBucket oAuth is not configured check the manually added user namespace token.
HttpBitbucketServerApiClient apiClient =
Expand All @@ -180,7 +181,7 @@ public Optional<Pair<Boolean, String>> isValid(PersonalAccessTokenParams params)
try {
BitbucketUser user = bitbucketServerApiClient.getUser(params.getToken());
return Optional.of(Pair.of(Boolean.TRUE, user.getName()));
} catch (ScmItemNotFoundException | ScmUnauthorizedException | ScmCommunicationException e) {
} catch (ScmItemNotFoundException | ScmUnauthorizedException e) {
return Optional.empty();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ private boolean isUserTokenPresent(String repositoryUrl) {
Optional<PersonalAccessToken> token =
personalAccessTokenManager.get(EnvironmentContext.getCurrent().getSubject(), serverUrl);
return token.isPresent() && token.get().getScmTokenName().equals(OAUTH_PROVIDER_NAME);
} catch (ScmConfigurationPersistenceException exception) {
} catch (ScmConfigurationPersistenceException | ScmCommunicationException exception) {
return false;
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2012-2023 Red Hat, Inc.
* Copyright (c) 2012-2024 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
Expand All @@ -15,6 +15,7 @@
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static java.time.Duration.ofSeconds;

import com.fasterxml.jackson.databind.ObjectMapper;
Expand All @@ -37,6 +38,7 @@
import org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException;
import org.eclipse.che.api.factory.server.scm.exception.ScmCommunicationException;
import org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException;
import org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException;
import org.eclipse.che.commons.lang.Pair;
import org.eclipse.che.commons.lang.concurrent.LoggingUncaughtExceptionHandler;
import org.slf4j.Logger;
Expand Down Expand Up @@ -100,7 +102,8 @@ public BitbucketApiClient() {
* @throws ScmBadRequestException
*/
public BitbucketUser getUser(String authenticationToken)
throws ScmItemNotFoundException, ScmCommunicationException, ScmBadRequestException {
throws ScmItemNotFoundException, ScmCommunicationException, ScmBadRequestException,
ScmUnauthorizedException {
final URI uri = apiServerUrl.resolve("user");
HttpRequest request = buildBitbucketApiRequest(uri, authenticationToken);
LOG.trace("executeRequest={}", request);
Expand All @@ -120,7 +123,8 @@ public BitbucketUser getUser(String authenticationToken)

public String getFileContent(
String workspace, String repository, String source, String path, String authenticationToken)
throws ScmItemNotFoundException, ScmCommunicationException, ScmBadRequestException {
throws ScmItemNotFoundException, ScmCommunicationException, ScmBadRequestException,
ScmUnauthorizedException {
final URI uri =
apiServerUrl.resolve(
String.format("repositories/%s/%s/src/%s/%s", workspace, repository, source, path));
Expand Down Expand Up @@ -148,7 +152,8 @@ public String getFileContent(
* @throws ScmBadRequestException
*/
public BitbucketUserEmail getEmail(String authenticationToken)
throws ScmItemNotFoundException, ScmCommunicationException, ScmBadRequestException {
throws ScmItemNotFoundException, ScmCommunicationException, ScmBadRequestException,
ScmUnauthorizedException {
final URI uri = apiServerUrl.resolve("user/emails");
HttpRequest request = buildBitbucketApiRequest(uri, authenticationToken);
LOG.trace("executeRequest={}", request);
Expand All @@ -174,7 +179,8 @@ public BitbucketUserEmail getEmail(String authenticationToken)
* scopes.
*/
public Pair<String, String[]> getTokenScopes(String authenticationToken)
throws ScmItemNotFoundException, ScmCommunicationException, ScmBadRequestException {
throws ScmItemNotFoundException, ScmCommunicationException, ScmBadRequestException,
ScmUnauthorizedException {
final URI uri = apiServerUrl.resolve("user");
HttpRequest request = buildBitbucketApiRequest(uri, authenticationToken);
LOG.trace("executeRequest={}", request);
Expand Down Expand Up @@ -212,7 +218,8 @@ private <T> T executeRequest(
HttpClient httpClient,
HttpRequest request,
Function<HttpResponse<InputStream>, T> responseConverter)
throws ScmBadRequestException, ScmItemNotFoundException, ScmCommunicationException {
throws ScmBadRequestException, ScmItemNotFoundException, ScmCommunicationException,
ScmUnauthorizedException {
try {
HttpResponse<InputStream> response =
httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream());
Expand All @@ -228,6 +235,8 @@ private <T> T executeRequest(
throw new ScmBadRequestException(body);
case HTTP_NOT_FOUND:
throw new ScmItemNotFoundException(body);
case HTTP_UNAUTHORIZED:
throw new ScmUnauthorizedException(body, "github", "v1", "");
default:
throw new ScmCommunicationException(
"Unexpected status code " + response.statusCode() + " " + response.toString());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,13 +166,17 @@ public Optional<Boolean> isValid(PersonalAccessToken personalAccessToken) {
try {
String[] scopes = bitbucketApiClient.getTokenScopes(personalAccessToken.getToken()).second;
return Optional.of(isValidScope(Sets.newHashSet(scopes)));
} catch (ScmItemNotFoundException | ScmCommunicationException | ScmBadRequestException e) {
} catch (ScmItemNotFoundException
| ScmCommunicationException
| ScmBadRequestException
| ScmUnauthorizedException e) {
return Optional.of(Boolean.FALSE);
}
}

@Override
public Optional<Pair<Boolean, String>> isValid(PersonalAccessTokenParams params) {
public Optional<Pair<Boolean, String>> isValid(PersonalAccessTokenParams params)
throws ScmCommunicationException {
if (!bitbucketApiClient.isConnected(params.getScmProviderUrl())) {
LOG.debug("not a valid url {} for current fetcher ", params.getScmProviderUrl());
return Optional.empty();
Expand All @@ -184,7 +188,7 @@ public Optional<Pair<Boolean, String>> isValid(PersonalAccessTokenParams params)
Pair.of(
isValidScope(Sets.newHashSet(pair.second)) ? Boolean.TRUE : Boolean.FALSE,
pair.first));
} catch (ScmItemNotFoundException | ScmCommunicationException | ScmBadRequestException e) {
} catch (ScmItemNotFoundException | ScmBadRequestException | ScmUnauthorizedException e) {
return Optional.empty();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static org.eclipse.che.api.factory.server.scm.PersonalAccessTokenFetcher.OAUTH_2_PREFIX;
import static org.eclipse.che.dto.server.DtoFactory.newDto;
import static org.mockito.ArgumentMatchers.anyString;
Expand Down Expand Up @@ -211,7 +211,7 @@ public void shouldValidateOauthToken() throws Exception {

@Test
public void shouldNotValidateExpiredOauthToken() throws Exception {
stubFor(get(urlEqualTo("/user")).willReturn(aResponse().withStatus(HTTP_FORBIDDEN)));
stubFor(get(urlEqualTo("/user")).willReturn(aResponse().withStatus(HTTP_UNAUTHORIZED)));

PersonalAccessTokenParams params =
new PersonalAccessTokenParams(
Expand All @@ -235,7 +235,7 @@ public void shouldThrowUnauthorizedExceptionIfTokenIsNotValid() throws Exception
stubFor(
get(urlEqualTo("/user"))
.withHeader(HttpHeaders.AUTHORIZATION, equalTo("token " + bitbucketOauthToken))
.willReturn(aResponse().withStatus(HTTP_FORBIDDEN)));
.willReturn(aResponse().withStatus(HTTP_UNAUTHORIZED)));

bitbucketPersonalAccessTokenFetcher.fetchPersonalAccessToken(
subject, BitbucketApiClient.BITBUCKET_SERVER);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,13 +215,17 @@ public Optional<Boolean> isValid(PersonalAccessToken personalAccessToken) {
return Optional.of(Boolean.FALSE);
}
}
} catch (ScmItemNotFoundException | ScmCommunicationException | ScmBadRequestException e) {
} catch (ScmItemNotFoundException
| ScmCommunicationException
| ScmBadRequestException
| ScmUnauthorizedException e) {
return Optional.of(Boolean.FALSE);
}
}

@Override
public Optional<Pair<Boolean, String>> isValid(PersonalAccessTokenParams params) {
public Optional<Pair<Boolean, String>> isValid(PersonalAccessTokenParams params)
throws ScmCommunicationException {
GithubApiClient apiClient;
if (githubApiClient.isConnected(params.getScmProviderUrl())) {
// The url from the token has the same url as the api client, no need to create a new one.
Expand All @@ -247,7 +251,7 @@ public Optional<Pair<Boolean, String>> isValid(PersonalAccessTokenParams params)
GithubUser user = apiClient.getUser(params.getToken());
return Optional.of(Pair.of(Boolean.TRUE, user.getLogin()));
}
} catch (ScmItemNotFoundException | ScmCommunicationException | ScmBadRequestException e) {
} catch (ScmItemNotFoundException | ScmBadRequestException | ScmUnauthorizedException e) {
return Optional.empty();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.lang.String.format;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static java.util.regex.Pattern.compile;
import static org.eclipse.che.api.factory.server.ApiExceptionMapper.toApiException;
import static org.eclipse.che.api.factory.server.github.GithubApiClient.GITHUB_SAAS_ENDPOINT;
Expand Down Expand Up @@ -121,7 +120,7 @@ private boolean isUserTokenPresent(String repositoryUrl) {
PersonalAccessToken accessToken = token.get();
return accessToken.getScmTokenName().equals(providerName);
}
} catch (ScmConfigurationPersistenceException exception) {
} catch (ScmConfigurationPersistenceException | ScmCommunicationException exception) {
return false;
}
}
Expand All @@ -137,14 +136,16 @@ private boolean isApiRequestRelevant(String repositoryUrl) {
// If the user request catches the unauthorised error, it means that the provided url
// belongs to GitHub.
githubApiClient.getUser("");
} catch (ScmCommunicationException e) {
return e.getStatusCode() == HTTP_UNAUTHORIZED
// Check the error message as well, because other providers might also return 401
// for such requests.
&& e.getMessage().contains("Requires authentication")
} catch (ScmUnauthorizedException e) {
// Check the error message as well, because other providers might also return 401
// for such requests.
return e.getMessage().contains("Requires authentication")
|| // for older GitHub Enterprise versions
e.getMessage().contains("Must authenticate to access this API.");
} catch (ScmItemNotFoundException | ScmBadRequestException | IllegalArgumentException e) {
} catch (ScmItemNotFoundException
| ScmBadRequestException
| IllegalArgumentException
| ScmCommunicationException e) {
return false;
}
}
Expand Down Expand Up @@ -289,7 +290,8 @@ private GithubPullRequest getPullRequest(
return apiClient.getPullRequest(pullRequestId, repoUser, repoName, null);
} catch (ScmItemNotFoundException
| ScmCommunicationException
| ScmBadRequestException exception) {
| ScmBadRequestException
| ScmUnauthorizedException exception) {
LOG.error("Failed to authenticate to GitHub", e);
}

Expand Down Expand Up @@ -340,7 +342,8 @@ private GithubCommit getLatestCommit(
} catch (ScmItemNotFoundException
| ScmCommunicationException
| ScmBadRequestException
| URISyntaxException exception) {
| URISyntaxException
| ScmUnauthorizedException exception) {
LOG.error("Failed to authenticate to GitHub", e);
}
} catch (ScmCommunicationException
Expand Down
Loading

0 comments on commit 46114a4

Please sign in to comment.