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