]> source.dussan.org Git - sonarqube.git/blob
97aa314537044d9976ab9189823c3874855814a8
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2022 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.bitbucketserver;
21
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.List;
25 import java.util.Optional;
26 import java.util.stream.Collectors;
27 import org.junit.Before;
28 import org.junit.BeforeClass;
29 import org.junit.Rule;
30 import org.junit.Test;
31 import org.sonar.alm.client.bitbucketserver.BitbucketServerRestClient;
32 import org.sonar.alm.client.bitbucketserver.Branch;
33 import org.sonar.alm.client.bitbucketserver.BranchesList;
34 import org.sonar.alm.client.bitbucketserver.Project;
35 import org.sonar.alm.client.bitbucketserver.Repository;
36 import org.sonar.api.server.ws.WebService;
37 import org.sonar.api.utils.System2;
38 import org.sonar.core.util.SequenceUuidFactory;
39 import org.sonar.db.DbTester;
40 import org.sonar.db.alm.pat.AlmPatDto;
41 import org.sonar.db.alm.setting.AlmSettingDto;
42 import org.sonar.db.component.BranchDto;
43 import org.sonar.db.project.ProjectDto;
44 import org.sonar.db.user.UserDto;
45 import org.sonar.server.almintegration.ws.ImportHelper;
46 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
47 import org.sonar.server.component.ComponentUpdater;
48 import org.sonar.server.es.TestProjectIndexers;
49 import org.sonar.server.exceptions.BadRequestException;
50 import org.sonar.server.exceptions.ForbiddenException;
51 import org.sonar.server.exceptions.NotFoundException;
52 import org.sonar.server.exceptions.UnauthorizedException;
53 import org.sonar.server.favorite.FavoriteUpdater;
54 import org.sonar.server.l18n.I18nRule;
55 import org.sonar.server.permission.PermissionTemplateService;
56 import org.sonar.server.project.ProjectDefaultVisibility;
57 import org.sonar.server.project.Visibility;
58 import org.sonar.server.tester.UserSessionRule;
59 import org.sonar.server.ws.WsActionTester;
60 import org.sonarqube.ws.Projects;
61
62 import static java.util.Objects.requireNonNull;
63 import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
64 import static org.apache.commons.lang.math.JVMRandom.nextLong;
65 import static org.assertj.core.api.Assertions.assertThat;
66 import static org.assertj.core.api.Assertions.assertThatThrownBy;
67 import static org.assertj.core.api.Assertions.tuple;
68 import static org.mockito.ArgumentMatchers.any;
69 import static org.mockito.Mockito.mock;
70 import static org.mockito.Mockito.verify;
71 import static org.mockito.Mockito.when;
72 import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto;
73 import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS;
74 import static org.sonar.db.permission.GlobalPermission.SCAN;
75
76 public class ImportBitbucketServerProjectActionTest {
77   private static final String GENERATED_PROJECT_KEY = "TEST_PROJECT_KEY";
78
79   @Rule
80   public UserSessionRule userSession = UserSessionRule.standalone();
81   @Rule
82   public DbTester db = DbTester.create();
83   @Rule
84   public final I18nRule i18n = new I18nRule();
85
86   private final ProjectDefaultVisibility projectDefaultVisibility = mock(ProjectDefaultVisibility.class);
87   private final BitbucketServerRestClient bitbucketServerRestClient = mock(BitbucketServerRestClient.class);
88
89   private final ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), i18n, System2.INSTANCE,
90     mock(PermissionTemplateService.class), new FavoriteUpdater(db.getDbClient()), new TestProjectIndexers(), new SequenceUuidFactory());
91
92   private final ImportHelper importHelper = new ImportHelper(db.getDbClient(), userSession);
93   private final ProjectKeyGenerator projectKeyGenerator = mock(ProjectKeyGenerator.class);
94   private final WsActionTester ws = new WsActionTester(new ImportBitbucketServerProjectAction(db.getDbClient(), userSession,
95     bitbucketServerRestClient, projectDefaultVisibility, componentUpdater, importHelper, projectKeyGenerator));
96
97   private static BranchesList defaultBranchesList;
98
99   @BeforeClass
100   public static void beforeAll() {
101     Branch defaultBranch = new Branch("default", true);
102     defaultBranchesList = new BranchesList(Collections.singletonList(defaultBranch));
103   }
104
105   @Before
106   public void before() {
107     when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE);
108     when(projectKeyGenerator.generateUniqueProjectKey(any(), any())).thenReturn(GENERATED_PROJECT_KEY);
109   }
110
111   @Test
112   public void import_project() {
113     UserDto user = db.users().insertUser();
114     userSession.logIn(user).addPermission(PROVISION_PROJECTS);
115     AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting();
116     db.almPats().insert(dto -> {
117       dto.setAlmSettingUuid(almSetting.getUuid());
118       dto.setUserUuid(user.getUuid());
119     });
120     Project project = getGsonBBSProject();
121     Repository repo = getGsonBBSRepo(project);
122     when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo);
123     when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(defaultBranchesList);
124
125     Projects.CreateWsResponse response = ws.newRequest()
126       .setParam("almSetting", almSetting.getKey())
127       .setParam("projectKey", "projectKey")
128       .setParam("repositorySlug", "repo-slug")
129       .executeProtobuf(Projects.CreateWsResponse.class);
130
131     Projects.CreateWsResponse.Project result = response.getProject();
132     assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY);
133     assertThat(result.getName()).isEqualTo(repo.getName());
134
135     Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
136     assertThat(projectDto).isPresent();
137     assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent();
138     verify(projectKeyGenerator).generateUniqueProjectKey(requireNonNull(project.getKey()), repo.getSlug());
139   }
140
141   @Test
142   public void fail_project_already_exist() {
143     UserDto user = db.users().insertUser();
144     userSession.logIn(user).addPermission(PROVISION_PROJECTS);
145     AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting();
146     db.almPats().insert(dto -> {
147       dto.setAlmSettingUuid(almSetting.getUuid());
148       dto.setUserUuid(user.getUuid());
149     });
150     Project project = getGsonBBSProject();
151     Repository repo = getGsonBBSRepo(project);
152     db.components().insertPublicProject(p -> p.setDbKey(GENERATED_PROJECT_KEY));
153
154     assertThatThrownBy(() -> {
155       when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo);
156       when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(defaultBranchesList);
157
158       ws.newRequest()
159         .setParam("almSetting", almSetting.getKey())
160         .setParam("projectKey", "projectKey")
161         .setParam("repositorySlug", "repo-slug")
162         .execute();
163     })
164       .isInstanceOf(BadRequestException.class)
165       .hasMessage("Could not create Project with key: \"%s\". A similar key already exists: \"%s\"", GENERATED_PROJECT_KEY, GENERATED_PROJECT_KEY);
166   }
167
168   @Test
169   public void fail_when_not_logged_in() {
170     assertThatThrownBy(() -> {
171       ws.newRequest()
172         .setParam("almSetting", "sdgfdshfjztutz")
173         .setParam("projectKey", "projectKey")
174         .setParam("repositorySlug", "repo-slug")
175         .execute();
176     })
177       .isInstanceOf(UnauthorizedException.class);
178   }
179
180   @Test
181   public void fail_when_missing_project_creator_permission() {
182     UserDto user = db.users().insertUser();
183     userSession.logIn(user).addPermission(SCAN);
184
185     assertThatThrownBy(() -> {
186       ws.newRequest()
187         .setParam("almSetting", "sdgfdshfjztutz")
188         .setParam("projectKey", "projectKey")
189         .setParam("repositorySlug", "repo-slug")
190         .execute();
191     })
192       .isInstanceOf(ForbiddenException.class)
193       .hasMessage("Insufficient privileges");
194   }
195
196   @Test
197   public void check_pat_is_missing() {
198     UserDto user = db.users().insertUser();
199     userSession.logIn(user).addPermission(PROVISION_PROJECTS);
200     AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting();
201
202     assertThatThrownBy(() -> {
203       ws.newRequest()
204         .setParam("almSetting", almSetting.getKey())
205         .execute();
206     })
207       .isInstanceOf(IllegalArgumentException.class)
208       .hasMessage("personal access token for '" + almSetting.getKey() + "' is missing");
209   }
210
211   @Test
212   public void fail_check_alm_setting_not_found() {
213     UserDto user = db.users().insertUser();
214     userSession.logIn(user).addPermission(PROVISION_PROJECTS);
215     AlmPatDto almPatDto = newAlmPatDto();
216     db.getDbClient().almPatDao().insert(db.getSession(), almPatDto, user.getLogin(), null);
217
218     assertThatThrownBy(() -> {
219       ws.newRequest()
220         .setParam("almSetting", "testKey")
221         .execute();
222     })
223       .isInstanceOf(NotFoundException.class)
224       .hasMessage("ALM Setting 'testKey' not found");
225   }
226
227   @Test
228   public void fail_when_no_creation_project_permission() {
229     UserDto user = db.users().insertUser();
230     userSession.logIn(user);
231
232     assertThatThrownBy(() -> {
233       ws.newRequest()
234         .setParam("almSetting", "anyvalue")
235         .execute();
236     })
237       .isInstanceOf(ForbiddenException.class)
238       .hasMessage("Insufficient privileges");
239   }
240
241   @Test
242   public void handle_givenNoDefaultBranchFound_doNotUpdateDefaultBranchName() {
243     BranchesList branchesList = new BranchesList();
244     Branch branch = new Branch("not_a_master", false);
245     branchesList.addBranch(branch);
246
247     UserDto user = db.users().insertUser();
248     userSession.logIn(user).addPermission(PROVISION_PROJECTS);
249     AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting();
250     db.almPats().insert(dto -> {
251       dto.setAlmSettingUuid(almSetting.getUuid());
252       dto.setUserUuid(user.getUuid());
253     });
254     Project project = getGsonBBSProject();
255     Repository repo = getGsonBBSRepo(project);
256     when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo);
257     when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(branchesList);
258
259     Projects.CreateWsResponse response = ws.newRequest()
260       .setParam("almSetting", almSetting.getKey())
261       .setParam("projectKey", "projectKey")
262       .setParam("repositorySlug", "repo-slug")
263       .executeProtobuf(Projects.CreateWsResponse.class);
264
265     Projects.CreateWsResponse.Project result = response.getProject();
266
267     Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
268
269     Collection<BranchDto> branchDtos = db.getDbClient().branchDao().selectByProject(db.getSession(), projectDto.get());
270     List<BranchDto> collect = branchDtos.stream().filter(BranchDto::isMain).collect(Collectors.toList());
271     String mainBranchName = collect.iterator().next().getKey();
272     assertThat(mainBranchName).isEqualTo("master");
273   }
274
275   @Test
276   public void handle_givenDefaultBranchNamedDefault_updateDefaultBranchNameToDefault() {
277     BranchesList branchesList = new BranchesList();
278     Branch branch = new Branch("default", true);
279     branchesList.addBranch(branch);
280
281     UserDto user = db.users().insertUser();
282     userSession.logIn(user).addPermission(PROVISION_PROJECTS);
283     AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting();
284     db.almPats().insert(dto -> {
285       dto.setAlmSettingUuid(almSetting.getUuid());
286       dto.setUserUuid(user.getUuid());
287     });
288     Project project = getGsonBBSProject();
289     Repository repo = getGsonBBSRepo(project);
290     when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo);
291     when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(branchesList);
292
293     Projects.CreateWsResponse response = ws.newRequest()
294       .setParam("almSetting", almSetting.getKey())
295       .setParam("projectKey", "projectKey")
296       .setParam("repositorySlug", "repo-slug")
297       .executeProtobuf(Projects.CreateWsResponse.class);
298
299     Projects.CreateWsResponse.Project result = response.getProject();
300
301     Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
302
303     Collection<BranchDto> branchDtos = db.getDbClient().branchDao().selectByProject(db.getSession(), projectDto.get());
304     List<BranchDto> collect = branchDtos.stream().filter(BranchDto::isMain).collect(Collectors.toList());
305     String mainBranchName = collect.iterator().next().getKey();
306     assertThat(mainBranchName).isEqualTo("default");
307   }
308
309   @Test
310   public void definition() {
311     WebService.Action def = ws.getDef();
312
313     assertThat(def.since()).isEqualTo("8.2");
314     assertThat(def.isPost()).isTrue();
315     assertThat(def.params())
316       .extracting(WebService.Param::key, WebService.Param::isRequired)
317       .containsExactlyInAnyOrder(
318         tuple("almSetting", true),
319         tuple("repositorySlug", true),
320         tuple("projectKey", true));
321   }
322
323   private Repository getGsonBBSRepo(Project project) {
324     Repository bbsResult = new Repository();
325     bbsResult.setProject(project);
326     bbsResult.setSlug(randomAlphanumeric(5));
327     bbsResult.setName(randomAlphanumeric(5));
328     bbsResult.setId(nextLong(100));
329     return bbsResult;
330   }
331
332   private Project getGsonBBSProject() {
333     return new Project()
334       .setKey(randomAlphanumeric(5))
335       .setId(nextLong(100))
336       .setName(randomAlphanumeric(5));
337   }
338
339 }