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