Skip to content

Commit

Permalink
Respect the ScmComunicationException on token validation step (#715)
Browse files Browse the repository at this point in the history
Throw the ScmCommunicationException on token validation step instead of returning invalid result.
Propagate the ScmCommunicationException to the dashboard as an ApiException.
Throw ScmUnauthorizedException on each scm api request with invalid token.
Log error instead of throwing RuntimeException on workspace provision steps.
  • Loading branch information
vinokurig authored Sep 13, 2024
1 parent c2a2fca commit 6121661
Show file tree
Hide file tree
Showing 28 changed files with 211 additions and 92 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
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 @@ -252,7 +252,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
@@ -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 Down Expand Up @@ -147,7 +147,9 @@ private <T> T executeRequest(
throw new ScmItemNotFoundException(body);
default:
throw new ScmCommunicationException(
"Unexpected status code " + response.statusCode() + " " + response.toString());
"Unexpected status code " + response.statusCode() + " " + response,
response.statusCode(),
"azure-devops");
}
}
} catch (IOException | InterruptedException | UncheckedIOException 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
Expand Up @@ -411,7 +411,9 @@ private <T> T executeRequest(
throw new ScmItemNotFoundException(body);
default:
throw new ScmCommunicationException(
"Unexpected status code " + response.statusCode() + " " + response.toString());
"Unexpected status code " + response.statusCode() + " " + response,
response.statusCode(),
"bitbucket");
}
}
} catch (IOException | InterruptedException | UncheckedIOException e) {
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,13 +235,17 @@ private <T> T executeRequest(
throw new ScmBadRequestException(body);
case HTTP_NOT_FOUND:
throw new ScmItemNotFoundException(body);
case HTTP_UNAUTHORIZED:
throw new ScmUnauthorizedException(body, "bitbucket", "v2", "");
default:
throw new ScmCommunicationException(
"Unexpected status code " + response.statusCode() + " " + response.toString());
"Unexpected status code " + response.statusCode() + " " + response,
response.statusCode(),
"bitbucket");
}
}
} catch (IOException | InterruptedException | UncheckedIOException e) {
throw new ScmCommunicationException(e.getMessage(), e);
throw new ScmCommunicationException(e.getMessage(), e, "bitbucket");
}
}

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
Loading

0 comments on commit 6121661

Please sign in to comment.