Skip to content

Commit

Permalink
Code cleanup
Browse files Browse the repository at this point in the history
Signed-off-by: Sergii Kabashniuk <skabashniuk@redhat.com>
  • Loading branch information
skabashnyuk committed Jan 18, 2021
1 parent 8a06b53 commit fe9872c
Show file tree
Hide file tree
Showing 10 changed files with 43 additions and 117 deletions.
4 changes: 0 additions & 4 deletions infrastructures/infrastructure-factory/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,6 @@
<groupId>org.eclipse.che.infrastructure</groupId>
<artifactId>infrastructure-kubernetes</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,10 @@
import com.google.common.collect.ImmutableMap;
import io.fabric8.kubernetes.api.model.LabelSelector;
import io.fabric8.kubernetes.api.model.LabelSelectorBuilder;
import io.fabric8.kubernetes.api.model.Namespace;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.ObjectMetaBuilder;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.SecretBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
Expand All @@ -43,16 +41,10 @@
import org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesClientFactory;
import org.eclipse.che.workspace.infrastructure.kubernetes.api.shared.KubernetesNamespaceMeta;
import org.eclipse.che.workspace.infrastructure.kubernetes.namespace.KubernetesNamespaceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Manages personal access token secrets used for private repositories authentication. */
@Singleton
public class KubernetesPersonalAccessTokenManager implements PersonalAccessTokenManager {

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

public static final Map<String, String> SECRET_LABELS =
ImmutableMap.of(
"app.kubernetes.io/part-of", "che.eclipse.org",
Expand Down Expand Up @@ -91,7 +83,6 @@ void save(PersonalAccessToken personalAccessToken)
throws UnsatisfiedScmPreconditionException, ScmConfigurationPersistenceException {
try {
String namespace = getFirstNamespace();
LOG.info(" save in namespace {}", namespace);
ObjectMeta meta =
new ObjectMetaBuilder()
.withName(NameGenerator.generate(NAME_PATTERN, 5))
Expand Down Expand Up @@ -143,9 +134,6 @@ public Optional<PersonalAccessToken> get(Subject cheUser, String scmServerUrl)
throws ScmConfigurationPersistenceException {

try {
String namespace = getFirstNamespace();
LOG.info(" save in namespace {}", namespace);

for (KubernetesNamespaceMeta namespaceMeta : namespaceFactory.list()) {
List<Secret> secrets =
namespaceFactory
Expand All @@ -170,8 +158,6 @@ public Optional<PersonalAccessToken> get(Subject cheUser, String scmServerUrl)
}
} catch (InfrastructureException e) {
throw new ScmConfigurationPersistenceException(e.getMessage(), e);
} catch (UnsatisfiedScmPreconditionException e) {
return Optional.empty();
}
return Optional.empty();
}
Expand All @@ -192,26 +178,4 @@ private String getFirstNamespace()
throw new ScmConfigurationPersistenceException(e.getMessage(), e);
}
}

private boolean canCreateDeleteSecrets(Namespace namespace) {
LOG.info("testing namespace {}", namespace);
ObjectMeta meta =
new ObjectMetaBuilder().withName(NameGenerator.generate(NAME_PATTERN, "tmp", 5)).build();
Secret secret = new SecretBuilder().withMetadata(meta).build();
try {
KubernetesClient kubernetesClient = clientFactory.create();
Secret result =
kubernetesClient
.secrets()
.inNamespace(namespace.getMetadata().getName())
.createOrReplace(secret);
kubernetesClient.secrets().delete(result);
LOG.info(" namespace {} is ok", namespace);
return true;
} catch (InfrastructureException e) {
LOG.error(e.getMessage(), e);
}
LOG.info(" namespace {} is not ok", namespace);
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@
*/
package org.eclipse.che.security.oauth1;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;

/**
* OAuth1 authentication for Bitbucket Server account.
Expand All @@ -23,12 +21,8 @@
@Singleton
public class BitbucketServerOAuthAuthenticator extends OAuthAuthenticator {

@Inject
public BitbucketServerOAuthAuthenticator(
@Named("che.oauth1.bitbucket.consumerkey") String consumerKey,
@Named("che.oauth1.bitbucket.privatekey") String privateKey,
@Named("che.oauth1.bitbucket.endpoint") String bitbucketEndpoint,
@Named("che.api") String apiEndpoint) {
String consumerKey, String privateKey, String bitbucketEndpoint, String apiEndpoint) {
super(
consumerKey,
bitbucketEndpoint + "/plugins/servlet/oauth/request-token",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public BitbucketServerOAuthAuthenticatorProvider(

authenticator =
getOAuthAuthenticator(consumerKeyPath, privateKeyPath, bitbucketEndpoint, apiEndpoint);
LOG.info("authenticator={}", authenticator);
LOG.debug("{} Bitbucket OAuthAuthenticator is used.", authenticator);
}

@Override
Expand All @@ -51,11 +51,9 @@ public OAuthAuthenticator get() {
private static OAuthAuthenticator getOAuthAuthenticator(
String consumerKeyPath, String privateKeyPath, String bitbucketEndpoint, String apiEndpoint)
throws IOException {
LOG.info("1");
if (!isNullOrEmpty(bitbucketEndpoint) && consumerKeyPath != null && privateKeyPath != null) {
String consumerKey = Files.readString(Path.of(consumerKeyPath));
String privateKey = Files.readString(Path.of(privateKeyPath));
LOG.info("consumerKey={} privateKey={}", consumerKey, privateKey);
if (!isNullOrEmpty(consumerKey) && !isNullOrEmpty(privateKey)) {
return new BitbucketServerOAuthAuthenticator(
consumerKey, privateKey, bitbucketEndpoint, apiEndpoint);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,14 @@ public BitbucketServerPersonalAccessTokenFetcher(
public PersonalAccessToken fetchPersonalAccessToken(Subject cheUser, String scmServerUrl)
throws ScmUnauthorizedException, ScmCommunicationException {
if (!bitbucketServerApi.isConnected(scmServerUrl)) {
LOG.info("not valid url {} for current fetcher ", scmServerUrl);
LOG.debug("not a valid url {} for current fetcher ", scmServerUrl);
return null;
}

String tokenName = format(TOKEN_NAME_TEMPLATE, cheUser.getUserId(), apiEndpoint.getHost());
try {
BitbucketUser user = bitbucketServerApi.getUser(EnvironmentContext.getCurrent().getSubject());
LOG.info("Current bitbucket user {} ", user);
LOG.debug("Current bitbucket user {} ", user);
// cleanup existed
List<BitbucketPersonalAccessToken> existedTokens =
bitbucketServerApi
Expand All @@ -75,14 +75,14 @@ public PersonalAccessToken fetchPersonalAccessToken(Subject cheUser, String scmS
.filter(p -> p.getName().equals(tokenName))
.collect(Collectors.toList());
for (BitbucketPersonalAccessToken existedToken : existedTokens) {
LOG.info("Deleting existed che token {} {}", existedToken.getId(), existedToken.getName());
LOG.debug("Deleting existed che token {} {}", existedToken.getId(), existedToken.getName());
bitbucketServerApi.deletePersonalAccessTokens(user.getSlug(), existedToken.getId());
}

BitbucketPersonalAccessToken token =
bitbucketServerApi.createPersonalAccessTokens(
user.getSlug(), tokenName, ImmutableSet.of("PROJECT_WRITE", "REPO_WRITE"));
LOG.info("Token = {} for {}", token.getId(), token.getUser());
LOG.debug("Token created = {} for {}", token.getId(), token.getUser());
return new PersonalAccessToken(
scmServerUrl,
EnvironmentContext.getCurrent().getSubject().getUserId(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@
import org.eclipse.che.api.factory.server.urlfactory.DevfileFilenamesProvider;
import org.eclipse.che.commons.annotation.Nullable;
import org.eclipse.che.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Parser of String Bitbucket URLs and provide {@link BitbucketUrl} objects.
Expand All @@ -35,7 +33,7 @@
*/
@Singleton
public class BitbucketURLParser {
private static final Logger LOG = LoggerFactory.getLogger(BitbucketURLParser.class);

private final DevfileFilenamesProvider devfileFilenamesProvider;
private static final String bitbucketUrlPatternTemplate =
"^(?<host>%s)/scm/(?<project>[^/]++)/(?<repo>[^.]++).git(\\?at=)?(?<branch>[\\w\\d-_]*)";
Expand All @@ -45,7 +43,6 @@ public class BitbucketURLParser {
public BitbucketURLParser(
@Nullable @Named("che.integration.bitbucket.server_endpoints") String bitbucketEndpoints,
DevfileFilenamesProvider devfileFilenamesProvider) {
LOG.info("bitbucketEndpoints={}", bitbucketEndpoints);
this.devfileFilenamesProvider = devfileFilenamesProvider;
if (bitbucketEndpoints != null) {
for (String bitbucketEndpoint : Splitter.on(",").split(bitbucketEndpoints)) {
Expand All @@ -57,7 +54,6 @@ public BitbucketURLParser(
}

public boolean isValid(@NotNull String url) {
LOG.info("isValid={}", url);
return !bitbucketUrlPatterns.isEmpty()
&& bitbucketUrlPatterns.stream().anyMatch(pattern -> pattern.matcher(url).matches());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,12 @@
import org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException;
import org.eclipse.che.commons.subject.Subject;

/** Bitbucket Server API client. */
public interface BitbucketServerApi {

/**
* @param bitbucketServerUrl
* @return - true if client is connected to the given bitbucket server.
*/
boolean isConnected(String bitbucketServerUrl);
/**
* @param cheUser - Che user.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

import static java.time.Duration.ofSeconds;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
Expand Down Expand Up @@ -44,6 +45,10 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Implementation of @{@link BitbucketServerApi} that is using @{@link HttpClient} to communicate
* with Bitbucket Server.s
*/
public class BitbucketServerApiHttpClient implements BitbucketServerApi {

private static final ObjectMapper OM = new ObjectMapper();
Expand All @@ -61,9 +66,7 @@ public BitbucketServerApiHttpClient(

@Override
public boolean isConnected(String bitbucketServerUrl) {
boolean equals = serverUri.equals(URI.create(bitbucketServerUrl));
LOG.info("{}={}={}", serverUri, bitbucketServerUrl, equals);
return equals;
return serverUri.equals(URI.create(bitbucketServerUrl));
}

@Override
Expand Down Expand Up @@ -112,6 +115,7 @@ public BitbucketUser getUser(String slug)
.build();

try {
LOG.debug("executeRequest={}", request);
return executeRequest(
httpClient,
request,
Expand Down Expand Up @@ -166,6 +170,7 @@ public void deletePersonalAccessTokens(String userSlug, Long tokenId)
.build();

try {
LOG.debug("executeRequest={}", request);
executeRequest(
httpClient,
request,
Expand All @@ -187,22 +192,24 @@ public BitbucketPersonalAccessToken createPersonalAccessTokens(
throws ScmBadRequestException, ScmUnauthorizedException, ScmCommunicationException {
HttpClient httpClient = HttpClient.newHttpClient();
URI uri = serverUri.resolve("/rest/access-tokens/1.0/users/" + userSlug);
HttpRequest request =
HttpRequest.newBuilder(uri)
.PUT(
JsonBodyPublishers.fromObject(
new BitbucketPersonalAccessToken(tokenName, permissions)))
.headers(
HttpHeaders.AUTHORIZATION,
headerProvider.computeAuthorizationHeader("PUT", uri.toString()),
HttpHeaders.ACCEPT,
MediaType.APPLICATION_JSON,
HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON)
.timeout(ofSeconds(10))
.build();

try {
HttpRequest request =
HttpRequest.newBuilder(uri)
.PUT(
HttpRequest.BodyPublishers.ofString(
OM.writeValueAsString(
new BitbucketPersonalAccessToken(tokenName, permissions))))
.headers(
HttpHeaders.AUTHORIZATION,
headerProvider.computeAuthorizationHeader("PUT", uri.toString()),
HttpHeaders.ACCEPT,
MediaType.APPLICATION_JSON,
HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON)
.timeout(ofSeconds(10))
.build();
LOG.debug("executeRequest={}", request);
return executeRequest(
httpClient,
request,
Expand All @@ -213,7 +220,7 @@ public BitbucketPersonalAccessToken createPersonalAccessTokens(
throw new UncheckedIOException(e);
}
});
} catch (ScmItemNotFoundException e) {
} catch (ScmItemNotFoundException | JsonProcessingException e) {
throw new ScmCommunicationException(e.getMessage(), e);
}
}
Expand All @@ -232,9 +239,7 @@ public List<BitbucketPersonalAccessToken> getPersonalAccessTokens(String userSlu
private Optional<BitbucketUser> findCurrentUser(Set<String> userSlugs)
throws ScmCommunicationException, ScmUnauthorizedException, ScmItemNotFoundException {

LOG.info("Testing {} items {}", userSlugs.size(), userSlugs);
for (String userSlug : userSlugs) {
LOG.info("findCurrentUser={}", userSlug);
BitbucketUser user = getUser(userSlug);
try {
getPersonalAccessTokens(userSlug);
Expand Down Expand Up @@ -275,6 +280,7 @@ private <T> Page<T> doGetPage(Class<T> tClass, String api, int start, int limit,
"Authorization", headerProvider.computeAuthorizationHeader("GET", uri.toString()))
.timeout(ofSeconds(10))
.build();
LOG.debug("executeRequest={}", request);
final JavaType typeReference =
TypeFactory.defaultInstance().constructParametricType(Page.class, tClass);
return executeRequest(
Expand All @@ -296,7 +302,7 @@ private <T> T executeRequest(
try {
HttpResponse<InputStream> response =
httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream());
LOG.info("executeRequest={} response {}", request, response.statusCode());
LOG.debug("executeRequest={} response {}", request, response.statusCode());
if (response.statusCode() == 200) {
return function.apply(response.body());
} else if (response.statusCode() == 204) {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
import org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException;
import org.eclipse.che.commons.subject.Subject;

/**
* Implementation of @{@link BitbucketServerApi} that is going to be deployed in container in case
* if no integration with Bitbucket server is needed.
*/
public class NopBitbucketServerApi implements BitbucketServerApi {
@Override
public boolean isConnected(String bitbucketServerUrl) {
Expand Down

0 comments on commit fe9872c

Please sign in to comment.