]> source.dussan.org Git - sonarqube.git/blob
13f4dea54e5925223bfa644302aed1194df69f1d
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2023 SonarSource SA
4  * mailto:info AT sonarsource DOT com
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 3 of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19  */
20 package org.sonar.server.almintegration.ws.github;
21
22 import java.util.Objects;
23 import java.util.Optional;
24 import javax.inject.Inject;
25 import org.sonar.alm.client.github.GithubApplicationClient;
26 import org.sonar.alm.client.github.GithubApplicationClient.Repository;
27 import org.sonar.alm.client.github.GithubApplicationClientImpl;
28 import org.sonar.alm.client.github.security.AccessToken;
29 import org.sonar.alm.client.github.security.UserAccessToken;
30 import org.sonar.api.server.ws.Change;
31 import org.sonar.api.server.ws.Request;
32 import org.sonar.api.server.ws.Response;
33 import org.sonar.api.server.ws.WebService;
34 import org.sonar.auth.github.GitHubSettings;
35 import org.sonar.db.DbClient;
36 import org.sonar.db.DbSession;
37 import org.sonar.db.alm.pat.AlmPatDto;
38 import org.sonar.db.alm.setting.AlmSettingDto;
39 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
40 import org.sonar.db.component.BranchDto;
41 import org.sonar.db.project.ProjectDto;
42 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
43 import org.sonar.server.almintegration.ws.ImportHelper;
44 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
45 import org.sonar.server.component.ComponentCreationData;
46 import org.sonar.server.component.ComponentCreationParameters;
47 import org.sonar.server.component.ComponentUpdater;
48 import org.sonar.server.component.NewComponent;
49 import org.sonar.server.exceptions.NotFoundException;
50 import org.sonar.server.management.ManagedProjectService;
51 import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
52 import org.sonar.server.project.DefaultBranchNameResolver;
53 import org.sonar.server.project.ProjectDefaultVisibility;
54 import org.sonar.server.user.UserSession;
55 import org.sonarqube.ws.Projects;
56
57 import static java.util.Objects.requireNonNull;
58 import static org.sonar.api.resources.Qualifiers.PROJECT;
59 import static org.sonar.db.project.CreationMethod.Category.ALM_IMPORT;
60 import static org.sonar.db.project.CreationMethod.getCreationMethod;
61 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
62 import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
63 import static org.sonar.server.component.NewComponent.newComponentBuilder;
64 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
65 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
66 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
67 import static org.sonar.server.ws.WsUtils.writeProtobuf;
68 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
69 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
70
71 public class ImportGithubProjectAction implements AlmIntegrationsWsAction {
72
73   public static final String PARAM_ORGANIZATION = "organization";
74   public static final String PARAM_REPOSITORY_KEY = "repositoryKey";
75
76   private final DbClient dbClient;
77
78   private final ManagedProjectService managedProjectService;
79   private final UserSession userSession;
80   private final ProjectDefaultVisibility projectDefaultVisibility;
81   private final GithubApplicationClient githubApplicationClient;
82   private final ComponentUpdater componentUpdater;
83   private final ImportHelper importHelper;
84   private final ProjectKeyGenerator projectKeyGenerator;
85
86   private final NewCodeDefinitionResolver newCodeDefinitionResolver;
87
88   private final DefaultBranchNameResolver defaultBranchNameResolver;
89
90   private final GitHubSettings gitHubSettings;
91
92   @Inject
93   public ImportGithubProjectAction(DbClient dbClient, ManagedProjectService managedProjectService, UserSession userSession, ProjectDefaultVisibility projectDefaultVisibility,
94     GithubApplicationClientImpl githubApplicationClient, ComponentUpdater componentUpdater, ImportHelper importHelper,
95     ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
96     DefaultBranchNameResolver defaultBranchNameResolver, GitHubSettings gitHubSettings) {
97     this.dbClient = dbClient;
98     this.managedProjectService = managedProjectService;
99     this.userSession = userSession;
100     this.projectDefaultVisibility = projectDefaultVisibility;
101     this.githubApplicationClient = githubApplicationClient;
102     this.componentUpdater = componentUpdater;
103     this.importHelper = importHelper;
104     this.projectKeyGenerator = projectKeyGenerator;
105     this.newCodeDefinitionResolver = newCodeDefinitionResolver;
106     this.defaultBranchNameResolver = defaultBranchNameResolver;
107     this.gitHubSettings = gitHubSettings;
108   }
109
110   @Override
111   public void define(WebService.NewController context) {
112     WebService.NewAction action = context.createAction("import_github_project")
113       .setDescription("Create a SonarQube project with the information from the provided GitHub repository.<br/>" +
114         "Autoconfigure pull request decoration mechanism. If Automatic Provisioning is enable for GitHub, it will also synchronize permissions from the repository.<br/>" +
115         "Requires the 'Create Projects' permission")
116       .setPost(true)
117       .setSince("8.4")
118       .setHandler(this)
119       .setChangelog(
120         new Change("10.3", "Endpoint visibility change from internal to public"));
121
122     action.createParam(PARAM_ALM_SETTING)
123       .setRequired(true)
124       .setMaximumLength(200)
125       .setDescription("DevOps Platform setting key");
126
127     action.createParam(PARAM_ORGANIZATION)
128       .setRequired(true)
129       .setMaximumLength(200)
130       .setDescription("GitHub organization");
131
132     action.createParam(PARAM_REPOSITORY_KEY)
133       .setRequired(true)
134       .setMaximumLength(256)
135       .setDescription("GitHub repository key");
136
137     action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
138       .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
139       .setSince("10.1");
140
141     action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
142       .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
143       .setSince("10.1");
144   }
145
146   @Override
147   public void handle(Request request, Response response) {
148     Projects.CreateWsResponse createResponse = doHandle(request);
149     writeProtobuf(createResponse, request, response);
150   }
151
152   private Projects.CreateWsResponse doHandle(Request request) {
153     importHelper.checkProvisionProjectPermission();
154     AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
155
156     String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
157     String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
158     try (DbSession dbSession = dbClient.openSession(false)) {
159
160       AccessToken accessToken = getAccessToken(dbSession, almSettingDto);
161
162       String githubOrganization = request.mandatoryParam(PARAM_ORGANIZATION);
163       String repositoryKey = request.mandatoryParam(PARAM_REPOSITORY_KEY);
164
165       String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
166       Repository repository = githubApplicationClient.getRepository(url, accessToken, githubOrganization, repositoryKey)
167         .orElseThrow(() -> new NotFoundException(String.format("GitHub repository '%s' not found", repositoryKey)));
168
169       ComponentCreationData componentCreationData = createProject(dbSession, repository, repository.getDefaultBranch());
170       ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
171       BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
172
173       populatePRSetting(dbSession, repository, projectDto, almSettingDto);
174
175       checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
176
177       if (newCodeDefinitionType != null) {
178         newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
179           Optional.ofNullable(repository.getDefaultBranch()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
180           newCodeDefinitionType, newCodeDefinitionValue);
181       }
182
183       componentUpdater.commitAndIndex(dbSession, componentCreationData);
184
185       String userUuid = Objects.requireNonNull(userSession.getUuid());
186       managedProjectService.queuePermissionSyncTask(userUuid, mainBranchDto.getUuid(), projectDto.getUuid());
187
188       return toCreateResponse(projectDto);
189     }
190   }
191
192   private AccessToken getAccessToken(DbSession dbSession, AlmSettingDto almSettingDto) {
193     String userUuid = importHelper.getUserUuid();
194     return dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto)
195       .map(AlmPatDto::getPersonalAccessToken)
196       .map(UserAccessToken::new)
197       .orElseThrow(() -> new IllegalArgumentException("No personal access token found"));
198   }
199
200   private ComponentCreationData createProject(DbSession dbSession, Repository repo, String mainBranchName) {
201     boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
202     String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getFullName());
203     NewComponent projectComponent = newComponentBuilder()
204       .setKey(uniqueProjectKey)
205       .setName(repo.getName())
206       .setPrivate(visibility)
207       .setQualifier(PROJECT)
208       .build();
209     ComponentCreationParameters componentCreationParameters = ComponentCreationParameters.builder()
210       .newComponent(projectComponent)
211       .userLogin(userSession.getLogin())
212       .userUuid(userSession.getUuid())
213       .mainBranchName(mainBranchName)
214       .isManaged(gitHubSettings.isProvisioningEnabled())
215       .creationMethod(getCreationMethod(ALM_IMPORT, userSession.isAuthenticatedBrowserSession()))
216       .build();
217     return componentUpdater.createWithoutCommit(dbSession, componentCreationParameters);
218   }
219
220   private void populatePRSetting(DbSession dbSession, Repository repo, ProjectDto projectDto, AlmSettingDto almSettingDto) {
221     ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
222       .setAlmSettingUuid(almSettingDto.getUuid())
223       .setAlmRepo(repo.getFullName())
224       .setAlmSlug(null)
225       .setProjectUuid(projectDto.getUuid())
226       .setSummaryCommentEnabled(true)
227       .setMonorepo(false);
228     dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
229       projectDto.getName(), projectDto.getKey());
230   }
231 }