Search in sources :

Example 16 with UserAccessToken

use of org.sonar.alm.client.github.security.UserAccessToken in project sonarqube by SonarSource.

the class GithubApplicationClientImplTest method listRepositories_returns_pages_results.

@Test
public void listRepositories_returns_pages_results() throws IOException {
    String appUrl = "https://github.sonarsource.com";
    AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
    String responseJson = "{\n" + "  \"total_count\": 2,\n" + "  \"incomplete_results\": false,\n" + "  \"items\": [\n" + "    {\n" + "      \"id\": 3081286,\n" + "      \"node_id\": \"MDEwOlJlcG9zaXRvcnkzMDgxMjg2\",\n" + "      \"name\": \"HelloWorld\",\n" + "      \"full_name\": \"github/HelloWorld\",\n" + "      \"owner\": {\n" + "        \"login\": \"github\",\n" + "        \"id\": 872147,\n" + "        \"node_id\": \"MDQ6VXNlcjg3MjE0Nw==\",\n" + "        \"avatar_url\": \"https://github.sonarsource.com/images/error/octocat_happy.gif\",\n" + "        \"gravatar_id\": \"\",\n" + "        \"url\": \"https://github.sonarsource.com/api/v3/users/github\",\n" + "        \"received_events_url\": \"https://github.sonarsource.com/api/v3/users/github/received_events\",\n" + "        \"type\": \"User\"\n" + "      },\n" + "      \"private\": false,\n" + "      \"html_url\": \"https://github.com/github/HelloWorld\",\n" + "      \"description\": \"A C implementation of HelloWorld\",\n" + "      \"fork\": false,\n" + "      \"url\": \"https://github.sonarsource.com/api/v3/repos/github/HelloWorld\",\n" + "      \"created_at\": \"2012-01-01T00:31:50Z\",\n" + "      \"updated_at\": \"2013-01-05T17:58:47Z\",\n" + "      \"pushed_at\": \"2012-01-01T00:37:02Z\",\n" + "      \"homepage\": \"\",\n" + "      \"size\": 524,\n" + "      \"stargazers_count\": 1,\n" + "      \"watchers_count\": 1,\n" + "      \"language\": \"Assembly\",\n" + "      \"forks_count\": 0,\n" + "      \"open_issues_count\": 0,\n" + "      \"master_branch\": \"master\",\n" + "      \"default_branch\": \"master\",\n" + "      \"score\": 1.0\n" + "    },\n" + "    {\n" + "      \"id\": 3081286,\n" + "      \"node_id\": \"MDEwOlJlcG9zaXRvcnkzMDgxMjg2\",\n" + "      \"name\": \"HelloUniverse\",\n" + "      \"full_name\": \"github/HelloUniverse\",\n" + "      \"owner\": {\n" + "        \"login\": \"github\",\n" + "        \"id\": 872147,\n" + "        \"node_id\": \"MDQ6VXNlcjg3MjE0Nw==\",\n" + "        \"avatar_url\": \"https://github.sonarsource.com/images/error/octocat_happy.gif\",\n" + "        \"gravatar_id\": \"\",\n" + "        \"url\": \"https://github.sonarsource.com/api/v3/users/github\",\n" + "        \"received_events_url\": \"https://github.sonarsource.com/api/v3/users/github/received_events\",\n" + "        \"type\": \"User\"\n" + "      },\n" + "      \"private\": false,\n" + "      \"html_url\": \"https://github.com/github/HelloUniverse\",\n" + "      \"description\": \"A C implementation of HelloUniverse\",\n" + "      \"fork\": false,\n" + "      \"url\": \"https://github.sonarsource.com/api/v3/repos/github/HelloUniverse\",\n" + "      \"created_at\": \"2012-01-01T00:31:50Z\",\n" + "      \"updated_at\": \"2013-01-05T17:58:47Z\",\n" + "      \"pushed_at\": \"2012-01-01T00:37:02Z\",\n" + "      \"homepage\": \"\",\n" + "      \"size\": 524,\n" + "      \"stargazers_count\": 1,\n" + "      \"watchers_count\": 1,\n" + "      \"language\": \"Assembly\",\n" + "      \"forks_count\": 0,\n" + "      \"open_issues_count\": 0,\n" + "      \"master_branch\": \"master\",\n" + "      \"default_branch\": \"master\",\n" + "      \"score\": 1.0\n" + "    }\n" + "  ]\n" + "}";
    when(httpClient.get(appUrl, accessToken, String.format("/search/repositories?q=%s&page=%s&per_page=%s", "fork:true+org:github", 1, 100))).thenReturn(new OkGetResponse(responseJson));
    GithubApplicationClient.Repositories repositories = underTest.listRepositories(appUrl, accessToken, "github", null, 1, 100);
    assertThat(repositories.getTotal()).isEqualTo(2);
    assertThat(repositories.getRepositories()).extracting(GithubApplicationClient.Repository::getName, GithubApplicationClient.Repository::getFullName).containsOnly(tuple("HelloWorld", "github/HelloWorld"), tuple("HelloUniverse", "github/HelloUniverse"));
}
Also used : UserAccessToken(org.sonar.alm.client.github.security.UserAccessToken) AccessToken(org.sonar.alm.client.github.security.AccessToken) UserAccessToken(org.sonar.alm.client.github.security.UserAccessToken) Test(org.junit.Test)

Example 17 with UserAccessToken

use of org.sonar.alm.client.github.security.UserAccessToken in project sonarqube by SonarSource.

the class GithubApplicationClientImplTest method listOrganizations_returns_pages_results.

@Test
public void listOrganizations_returns_pages_results() throws IOException {
    String appUrl = "https://github.sonarsource.com";
    AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
    String responseJson = "{\n" + "  \"total_count\": 2,\n" + "  \"installations\": [\n" + "    {\n" + "      \"id\": 1,\n" + "      \"account\": {\n" + "        \"login\": \"github\",\n" + "        \"id\": 1,\n" + "        \"node_id\": \"MDEyOk9yZ2FuaXphdGlvbjE=\",\n" + "        \"url\": \"https://github.sonarsource.com/api/v3/orgs/github\",\n" + "        \"repos_url\": \"https://github.sonarsource.com/api/v3/orgs/github/repos\",\n" + "        \"events_url\": \"https://github.sonarsource.com/api/v3/orgs/github/events\",\n" + "        \"hooks_url\": \"https://github.sonarsource.com/api/v3/orgs/github/hooks\",\n" + "        \"issues_url\": \"https://github.sonarsource.com/api/v3/orgs/github/issues\",\n" + "        \"members_url\": \"https://github.sonarsource.com/api/v3/orgs/github/members{/member}\",\n" + "        \"public_members_url\": \"https://github.sonarsource.com/api/v3/orgs/github/public_members{/member}\",\n" + "        \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\",\n" + "        \"description\": \"A great organization\"\n" + "      },\n" + "      \"access_tokens_url\": \"https://github.sonarsource.com/api/v3/app/installations/1/access_tokens\",\n" + "      \"repositories_url\": \"https://github.sonarsource.com/api/v3/installation/repositories\",\n" + "      \"html_url\": \"https://github.com/organizations/github/settings/installations/1\",\n" + "      \"app_id\": 1,\n" + "      \"target_id\": 1,\n" + "      \"target_type\": \"Organization\",\n" + "      \"permissions\": {\n" + "        \"checks\": \"write\",\n" + "        \"metadata\": \"read\",\n" + "        \"contents\": \"read\"\n" + "      },\n" + "      \"events\": [\n" + "        \"push\",\n" + "        \"pull_request\"\n" + "      ],\n" + "      \"single_file_name\": \"config.yml\"\n" + "    },\n" + "    {\n" + "      \"id\": 3,\n" + "      \"account\": {\n" + "        \"login\": \"octocat\",\n" + "        \"id\": 2,\n" + "        \"node_id\": \"MDQ6VXNlcjE=\",\n" + "        \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\",\n" + "        \"gravatar_id\": \"\",\n" + "        \"url\": \"https://github.sonarsource.com/api/v3/users/octocat\",\n" + "        \"html_url\": \"https://github.com/octocat\",\n" + "        \"followers_url\": \"https://github.sonarsource.com/api/v3/users/octocat/followers\",\n" + "        \"following_url\": \"https://github.sonarsource.com/api/v3/users/octocat/following{/other_user}\",\n" + "        \"gists_url\": \"https://github.sonarsource.com/api/v3/users/octocat/gists{/gist_id}\",\n" + "        \"starred_url\": \"https://github.sonarsource.com/api/v3/users/octocat/starred{/owner}{/repo}\",\n" + "        \"subscriptions_url\": \"https://github.sonarsource.com/api/v3/users/octocat/subscriptions\",\n" + "        \"organizations_url\": \"https://github.sonarsource.com/api/v3/users/octocat/orgs\",\n" + "        \"repos_url\": \"https://github.sonarsource.com/api/v3/users/octocat/repos\",\n" + "        \"events_url\": \"https://github.sonarsource.com/api/v3/users/octocat/events{/privacy}\",\n" + "        \"received_events_url\": \"https://github.sonarsource.com/api/v3/users/octocat/received_events\",\n" + "        \"type\": \"User\",\n" + "        \"site_admin\": false\n" + "      },\n" + "      \"access_tokens_url\": \"https://github.sonarsource.com/api/v3/app/installations/1/access_tokens\",\n" + "      \"repositories_url\": \"https://github.sonarsource.com/api/v3/installation/repositories\",\n" + "      \"html_url\": \"https://github.com/organizations/github/settings/installations/1\",\n" + "      \"app_id\": 1,\n" + "      \"target_id\": 1,\n" + "      \"target_type\": \"Organization\",\n" + "      \"permissions\": {\n" + "        \"checks\": \"write\",\n" + "        \"metadata\": \"read\",\n" + "        \"contents\": \"read\"\n" + "      },\n" + "      \"events\": [\n" + "        \"push\",\n" + "        \"pull_request\"\n" + "      ],\n" + "      \"single_file_name\": \"config.yml\"\n" + "    }\n" + "  ]\n" + "} ";
    when(httpClient.get(appUrl, accessToken, String.format("/user/installations?page=%s&per_page=%s", 1, 100))).thenReturn(new OkGetResponse(responseJson));
    GithubApplicationClient.Organizations organizations = underTest.listOrganizations(appUrl, accessToken, 1, 100);
    assertThat(organizations.getTotal()).isEqualTo(2);
    assertThat(organizations.getOrganizations()).extracting(GithubApplicationClient.Organization::getLogin).containsOnly("github", "octocat");
}
Also used : UserAccessToken(org.sonar.alm.client.github.security.UserAccessToken) AccessToken(org.sonar.alm.client.github.security.AccessToken) UserAccessToken(org.sonar.alm.client.github.security.UserAccessToken) Test(org.junit.Test)

Example 18 with UserAccessToken

use of org.sonar.alm.client.github.security.UserAccessToken in project sonarqube by SonarSource.

the class GithubApplicationClientImplTest method getRepository_fails_on_failure.

@Test
public void getRepository_fails_on_failure() throws IOException {
    String repositoryKey = "octocat/Hello-World";
    String organization = "octocat";
    when(httpClient.get(any(), any(), any())).thenThrow(new IOException("OOPS"));
    UserAccessToken token = new UserAccessToken("temp");
    assertThatThrownBy(() -> underTest.getRepository(appUrl, token, organization, repositoryKey)).isInstanceOf(IllegalStateException.class).hasMessage("Failed to get repository '%s' of '%s' accessible by user access token on '%s'", repositoryKey, organization, appUrl);
}
Also used : UserAccessToken(org.sonar.alm.client.github.security.UserAccessToken) IOException(java.io.IOException) Test(org.junit.Test)

Example 19 with UserAccessToken

use of org.sonar.alm.client.github.security.UserAccessToken in project sonarqube by SonarSource.

the class ImportGithubProjectAction method doHandle.

private Projects.CreateWsResponse doHandle(Request request) {
    importHelper.checkProvisionProjectPermission();
    AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
    String userUuid = importHelper.getUserUuid();
    try (DbSession dbSession = dbClient.openSession(false)) {
        AccessToken accessToken = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto).map(AlmPatDto::getPersonalAccessToken).map(UserAccessToken::new).orElseThrow(() -> new IllegalArgumentException("No personal access token found"));
        String githubOrganization = request.mandatoryParam(PARAM_ORGANIZATION);
        String repositoryKey = request.mandatoryParam(PARAM_REPOSITORY_KEY);
        String url = requireNonNull(almSettingDto.getUrl(), "ALM url cannot be null");
        Repository repository = githubApplicationClient.getRepository(url, accessToken, githubOrganization, repositoryKey).orElseThrow(() -> new NotFoundException(String.format("GitHub repository '%s' not found", repositoryKey)));
        ComponentDto componentDto = createProject(dbSession, repository, repository.getDefaultBranch());
        populatePRSetting(dbSession, repository, componentDto, almSettingDto);
        componentUpdater.commitAndIndex(dbSession, componentDto);
        return toCreateResponse(componentDto);
    }
}
Also used : DbSession(org.sonar.db.DbSession) Repository(org.sonar.alm.client.github.GithubApplicationClient.Repository) UserAccessToken(org.sonar.alm.client.github.security.UserAccessToken) AccessToken(org.sonar.alm.client.github.security.AccessToken) AlmPatDto(org.sonar.db.alm.pat.AlmPatDto) ComponentDto(org.sonar.db.component.ComponentDto) NotFoundException(org.sonar.server.exceptions.NotFoundException) AlmSettingDto(org.sonar.db.alm.setting.AlmSettingDto) ProjectAlmSettingDto(org.sonar.db.alm.setting.ProjectAlmSettingDto)

Example 20 with UserAccessToken

use of org.sonar.alm.client.github.security.UserAccessToken in project sonarqube by SonarSource.

the class ListGithubRepositoriesAction method doHandle.

private AlmIntegrations.ListGithubRepositoriesWsResponse doHandle(Request request) {
    try (DbSession dbSession = dbClient.openSession(false)) {
        userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS);
        String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING);
        AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey).orElseThrow(() -> new NotFoundException(String.format("GitHub ALM Setting '%s' not found", almSettingKey)));
        String userUuid = requireNonNull(userSession.getUuid(), "User UUID is not null");
        String url = requireNonNull(almSettingDto.getUrl(), String.format("No URL set for GitHub ALM '%s'", almSettingKey));
        AccessToken accessToken = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto).map(AlmPatDto::getPersonalAccessToken).map(UserAccessToken::new).orElseThrow(() -> new IllegalArgumentException("No personal access token found"));
        int pageIndex = request.hasParam(PAGE) ? request.mandatoryParamAsInt(PAGE) : 1;
        int pageSize = request.hasParam(PAGE_SIZE) ? request.mandatoryParamAsInt(PAGE_SIZE) : 100;
        GithubApplicationClient.Repositories repositories = githubApplicationClient.listRepositories(url, accessToken, request.mandatoryParam(PARAM_ORGANIZATION), request.param(TEXT_QUERY), pageIndex, pageSize);
        AlmIntegrations.ListGithubRepositoriesWsResponse.Builder response = AlmIntegrations.ListGithubRepositoriesWsResponse.newBuilder().setPaging(Common.Paging.newBuilder().setPageIndex(pageIndex).setPageSize(pageSize).setTotal(repositories.getTotal()).build());
        List<Repository> repositoryList = repositories.getRepositories();
        if (repositoryList != null) {
            Set<String> repo = repositoryList.stream().map(Repository::getFullName).collect(Collectors.toSet());
            List<ProjectAlmSettingDto> projectAlmSettingDtos = projectAlmSettingDao.selectByAlmSettingAndRepos(dbSession, almSettingDto, repo);
            Map<String, ProjectDto> projectsDtoByAlmRepo = getProjectDtoByAlmRepo(dbSession, projectAlmSettingDtos);
            for (Repository repository : repositoryList) {
                AlmIntegrations.GithubRepository.Builder builder = AlmIntegrations.GithubRepository.newBuilder().setId(repository.getId()).setKey(repository.getFullName()).setName(repository.getName()).setUrl(repository.getUrl());
                if (projectsDtoByAlmRepo.containsKey(repository.getFullName())) {
                    Optional.ofNullable(projectsDtoByAlmRepo.get(repository.getFullName())).ifPresent(p -> builder.setSqProjectKey(p.getKey()));
                }
                response.addRepositories(builder.build());
            }
        }
        return response.build();
    }
}
Also used : ProjectDto(org.sonar.db.project.ProjectDto) GithubApplicationClient(org.sonar.alm.client.github.GithubApplicationClient) ProjectAlmSettingDto(org.sonar.db.alm.setting.ProjectAlmSettingDto) AlmPatDto(org.sonar.db.alm.pat.AlmPatDto) NotFoundException(org.sonar.server.exceptions.NotFoundException) DbSession(org.sonar.db.DbSession) Repository(org.sonar.alm.client.github.GithubApplicationClient.Repository) UserAccessToken(org.sonar.alm.client.github.security.UserAccessToken) AccessToken(org.sonar.alm.client.github.security.AccessToken) AlmSettingDto(org.sonar.db.alm.setting.AlmSettingDto) ProjectAlmSettingDto(org.sonar.db.alm.setting.ProjectAlmSettingDto)

Aggregations

UserAccessToken (org.sonar.alm.client.github.security.UserAccessToken)21 Test (org.junit.Test)18 AccessToken (org.sonar.alm.client.github.security.AccessToken)11 AlmSettingDto (org.sonar.db.alm.setting.AlmSettingDto)6 AlmPatDto (org.sonar.db.alm.pat.AlmPatDto)4 NotFoundException (org.sonar.server.exceptions.NotFoundException)4 ListGithubOrganizationsWsResponse (org.sonarqube.ws.AlmIntegrations.ListGithubOrganizationsWsResponse)4 IOException (java.io.IOException)3 GithubApplicationClient (org.sonar.alm.client.github.GithubApplicationClient)3 DbSession (org.sonar.db.DbSession)3 Common (org.sonarqube.ws.Common)3 Optional (java.util.Optional)2 Repository (org.sonar.alm.client.github.GithubApplicationClient.Repository)2 ProjectAlmSettingDto (org.sonar.db.alm.setting.ProjectAlmSettingDto)2 UseDataProvider (com.tngtech.java.junit.dataprovider.UseDataProvider)1 Collectors (java.util.stream.Collectors)1 Stream (java.util.stream.Stream)1 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)1 Assertions.assertThatThrownBy (org.assertj.core.api.Assertions.assertThatThrownBy)1 Assertions.tuple (org.assertj.core.api.Assertions.tuple)1