Search in sources :

Example 26 with PersonalAccessToken

use of org.eclipse.che.api.factory.server.scm.PersonalAccessToken in project devspaces-images by redhat-developer.

the class GithubPersonalAccessTokenFetcherTest method shouldValidatePersonalToken.

@Test
public void shouldValidatePersonalToken() throws Exception {
    stubFor(get(urlEqualTo("/user")).withHeader(HttpHeaders.AUTHORIZATION, equalTo("token " + githubOauthToken)).willReturn(aResponse().withHeader("Content-Type", "application/json; charset=utf-8").withHeader(GithubApiClient.GITHUB_OAUTH_SCOPES_HEADER, "repo").withBodyFile("github/rest/user/response.json")));
    PersonalAccessToken token = new PersonalAccessToken("https://github.com", "cheUser", "username", "123456789", "token-name", "tid-23434", githubOauthToken);
    assertTrue(githubPATFetcher.isValid(token).get());
}
Also used : PersonalAccessToken(org.eclipse.che.api.factory.server.scm.PersonalAccessToken) Test(org.testng.annotations.Test)

Example 27 with PersonalAccessToken

use of org.eclipse.che.api.factory.server.scm.PersonalAccessToken in project devspaces-images by redhat-developer.

the class GitlabOAuthTokenFetcher method fetchPersonalAccessToken.

@Override
public PersonalAccessToken fetchPersonalAccessToken(Subject cheSubject, String scmServerUrl) throws ScmUnauthorizedException, ScmCommunicationException {
    scmServerUrl = StringUtils.trimEnd(scmServerUrl, '/');
    GitlabApiClient gitlabApiClient = getApiClient(scmServerUrl);
    if (gitlabApiClient == null || !gitlabApiClient.isConnected(scmServerUrl)) {
        LOG.debug("not a  valid url {} for current fetcher ", scmServerUrl);
        return null;
    }
    if (oAuthAPI == null) {
        throw new ScmCommunicationException(format("OAuth 2 is not configured for SCM provider [%s]. For details, refer " + "the documentation in section of SCM providers configuration.", OAUTH_PROVIDER_NAME));
    }
    OAuthToken oAuthToken;
    try {
        oAuthToken = oAuthAPI.getToken(OAUTH_PROVIDER_NAME);
        GitlabUser user = gitlabApiClient.getUser(oAuthToken.getToken());
        PersonalAccessToken token = new PersonalAccessToken(scmServerUrl, cheSubject.getUserId(), user.getUsername(), Long.toString(user.getId()), NameGenerator.generate(OAUTH_2_PREFIX, 5), NameGenerator.generate("id-", 5), oAuthToken.getToken());
        Optional<Boolean> valid = isValid(token);
        if (valid.isEmpty() || !valid.get()) {
            throw new ScmCommunicationException("Current token doesn't have the necessary  privileges. Please make sure Che app scopes are correct and containing at least: " + DEFAULT_TOKEN_SCOPES.toString());
        }
        return token;
    } catch (UnauthorizedException e) {
        throw new ScmUnauthorizedException(cheSubject.getUserName() + " is not authorized in " + OAUTH_PROVIDER_NAME + " OAuth provider.", OAUTH_PROVIDER_NAME, "2.0", getLocalAuthenticateUrl());
    } catch (NotFoundException | ServerException | ForbiddenException | BadRequestException | ScmItemNotFoundException | ScmBadRequestException | ConflictException e) {
        LOG.warn(e.getMessage());
        throw new ScmCommunicationException(e.getMessage(), e);
    }
}
Also used : ForbiddenException(org.eclipse.che.api.core.ForbiddenException) ScmItemNotFoundException(org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException) ServerException(org.eclipse.che.api.core.ServerException) ConflictException(org.eclipse.che.api.core.ConflictException) ScmCommunicationException(org.eclipse.che.api.factory.server.scm.exception.ScmCommunicationException) ScmItemNotFoundException(org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException) NotFoundException(org.eclipse.che.api.core.NotFoundException) ScmBadRequestException(org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException) OAuthToken(org.eclipse.che.api.auth.shared.dto.OAuthToken) PersonalAccessToken(org.eclipse.che.api.factory.server.scm.PersonalAccessToken) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) ScmUnauthorizedException(org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException) ScmBadRequestException(org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException) BadRequestException(org.eclipse.che.api.core.BadRequestException) ScmUnauthorizedException(org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException)

Example 28 with PersonalAccessToken

use of org.eclipse.che.api.factory.server.scm.PersonalAccessToken in project devspaces-images by redhat-developer.

the class BitbucketServerPersonalAccessTokenFetcher method fetchPersonalAccessToken.

@Override
public PersonalAccessToken fetchPersonalAccessToken(Subject cheUser, String scmServerUrl) throws ScmUnauthorizedException, ScmCommunicationException {
    if (!bitbucketServerApiClient.isConnected(scmServerUrl)) {
        LOG.debug("not a  valid url {} for current fetcher ", scmServerUrl);
        return null;
    }
    final String tokenName = format(TOKEN_NAME_TEMPLATE, cheUser.getUserId(), apiEndpoint.getHost());
    try {
        BitbucketUser user = bitbucketServerApiClient.getUser(EnvironmentContext.getCurrent().getSubject());
        LOG.debug("Current bitbucket user {} ", user);
        // cleanup existed
        List<BitbucketPersonalAccessToken> existingTokens = bitbucketServerApiClient.getPersonalAccessTokens(user.getSlug()).stream().filter(p -> p.getName().equals(tokenName)).collect(Collectors.toList());
        for (BitbucketPersonalAccessToken existedToken : existingTokens) {
            LOG.debug("Deleting existed che token {} {}", existedToken.getId(), existedToken.getName());
            bitbucketServerApiClient.deletePersonalAccessTokens(user.getSlug(), existedToken.getId());
        }
        BitbucketPersonalAccessToken token = bitbucketServerApiClient.createPersonalAccessTokens(user.getSlug(), tokenName, DEFAULT_TOKEN_SCOPE);
        LOG.debug("Token created = {} for {}", token.getId(), token.getUser());
        return new PersonalAccessToken(scmServerUrl, EnvironmentContext.getCurrent().getSubject().getUserId(), user.getName(), valueOf(user.getId()), token.getName(), valueOf(token.getId()), token.getToken());
    } catch (ScmBadRequestException | ScmItemNotFoundException e) {
        throw new ScmCommunicationException(e.getMessage(), e);
    }
}
Also used : ScmBadRequestException(org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException) ImmutableSet(com.google.common.collect.ImmutableSet) Logger(org.slf4j.Logger) URL(java.net.URL) ScmCommunicationException(org.eclipse.che.api.factory.server.scm.exception.ScmCommunicationException) ScmItemNotFoundException(org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) BitbucketServerApiClient(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketServerApiClient) PersonalAccessTokenFetcher(org.eclipse.che.api.factory.server.scm.PersonalAccessTokenFetcher) ScmUnauthorizedException(org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException) Inject(javax.inject.Inject) List(java.util.List) EnvironmentContext(org.eclipse.che.commons.env.EnvironmentContext) String.valueOf(java.lang.String.valueOf) BitbucketUser(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketUser) PersonalAccessToken(org.eclipse.che.api.factory.server.scm.PersonalAccessToken) Subject(org.eclipse.che.commons.subject.Subject) Optional(java.util.Optional) Named(javax.inject.Named) BitbucketPersonalAccessToken(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketPersonalAccessToken) ScmItemNotFoundException(org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException) PersonalAccessToken(org.eclipse.che.api.factory.server.scm.PersonalAccessToken) BitbucketPersonalAccessToken(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketPersonalAccessToken) ScmCommunicationException(org.eclipse.che.api.factory.server.scm.exception.ScmCommunicationException) BitbucketPersonalAccessToken(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketPersonalAccessToken) BitbucketUser(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketUser) ScmBadRequestException(org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException)

Example 29 with PersonalAccessToken

use of org.eclipse.che.api.factory.server.scm.PersonalAccessToken in project devspaces-images by redhat-developer.

the class BitbucketServerAuthorizingFileContentProviderTest method shouldResolveRelativePaths.

@Test(dataProvider = "relativePathsProvider")
public void shouldResolveRelativePaths(String relative, String expected, String branch) throws Exception {
    BitbucketUrl url = new BitbucketUrl().withHostName(TEST_HOSTNAME).withProject("proj").withRepository("repo").withDevfileFilenames(Collections.singletonList(".devfile"));
    if (branch != null) {
        url.withBranch(branch);
    }
    BitbucketServerAuthorizingFileContentProvider fileContentProvider = new BitbucketServerAuthorizingFileContentProvider(url, urlFetcher, gitCredentialManager, personalAccessTokenManager);
    PersonalAccessToken token = new PersonalAccessToken(TEST_HOSTNAME, "user1", "token");
    when(personalAccessTokenManager.get(any(Subject.class), anyString())).thenReturn(Optional.of(token));
    // when
    fileContentProvider.fetchContent(relative);
    // then
    verify(urlFetcher).fetch(eq(expected), eq("Bearer token"));
}
Also used : PersonalAccessToken(org.eclipse.che.api.factory.server.scm.PersonalAccessToken) Subject(org.eclipse.che.commons.subject.Subject) Test(org.testng.annotations.Test)

Example 30 with PersonalAccessToken

use of org.eclipse.che.api.factory.server.scm.PersonalAccessToken in project devspaces-images by redhat-developer.

the class BitbucketServerAuthorizingFileContentProviderTest method shouldFetchTokenIfNotYetPresent.

@Test
public void shouldFetchTokenIfNotYetPresent() throws Exception {
    BitbucketUrl url = new BitbucketUrl().withHostName(TEST_HOSTNAME);
    BitbucketServerAuthorizingFileContentProvider fileContentProvider = new BitbucketServerAuthorizingFileContentProvider(url, urlFetcher, gitCredentialManager, personalAccessTokenManager);
    PersonalAccessToken token = new PersonalAccessToken(TEST_HOSTNAME, "user1", "token");
    when(personalAccessTokenManager.get(any(Subject.class), anyString())).thenReturn(Optional.empty());
    when(personalAccessTokenManager.fetchAndSave(any(Subject.class), eq(TEST_HOSTNAME))).thenReturn(token);
    when(urlFetcher.fetch(anyString())).thenThrow(new IOException("unauthorized"));
    String fileURL = "https://foo.bar/scm/repo/.devfile";
    // when
    fileContentProvider.fetchContent(fileURL);
    // then
    verify(personalAccessTokenManager).fetchAndSave(any(Subject.class), eq(TEST_HOSTNAME));
    verify(urlFetcher).fetch(eq(fileURL), eq("Bearer token"));
    verify(gitCredentialManager).createOrReplace(eq(token));
}
Also used : PersonalAccessToken(org.eclipse.che.api.factory.server.scm.PersonalAccessToken) IOException(java.io.IOException) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Subject(org.eclipse.che.commons.subject.Subject) Test(org.testng.annotations.Test)

Aggregations

PersonalAccessToken (org.eclipse.che.api.factory.server.scm.PersonalAccessToken)54 Test (org.testng.annotations.Test)42 Secret (io.fabric8.kubernetes.api.model.Secret)20 KubernetesNamespaceMeta (org.eclipse.che.workspace.infrastructure.kubernetes.api.shared.KubernetesNamespaceMeta)20 Subject (org.eclipse.che.commons.subject.Subject)16 KubernetesNamespaceMetaImpl (org.eclipse.che.workspace.infrastructure.kubernetes.api.server.impls.KubernetesNamespaceMetaImpl)16 ObjectMeta (io.fabric8.kubernetes.api.model.ObjectMeta)12 ObjectMetaBuilder (io.fabric8.kubernetes.api.model.ObjectMetaBuilder)12 SecretBuilder (io.fabric8.kubernetes.api.model.SecretBuilder)12 SubjectImpl (org.eclipse.che.commons.subject.SubjectImpl)12 LabelSelector (io.fabric8.kubernetes.api.model.LabelSelector)8 OAuthToken (org.eclipse.che.api.auth.shared.dto.OAuthToken)8 BitbucketPersonalAccessToken (org.eclipse.che.api.factory.server.bitbucket.server.BitbucketPersonalAccessToken)8 KubernetesNamespace (org.eclipse.che.workspace.infrastructure.kubernetes.namespace.KubernetesNamespace)8 KubernetesSecrets (org.eclipse.che.workspace.infrastructure.kubernetes.namespace.KubernetesSecrets)8 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)8 Optional (java.util.Optional)6 ScmBadRequestException (org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException)6 ScmCommunicationException (org.eclipse.che.api.factory.server.scm.exception.ScmCommunicationException)6 ScmItemNotFoundException (org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException)6