]> source.dussan.org Git - sonarqube.git/blob
6e50410f731aff5346ab78a2a59e608659f6e2ee
[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.bitbucketcloud;
21
22 import java.util.Optional;
23 import org.junit.Before;
24 import org.junit.Rule;
25 import org.junit.Test;
26 import org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient;
27 import org.sonar.alm.client.bitbucket.bitbucketcloud.MainBranch;
28 import org.sonar.alm.client.bitbucket.bitbucketcloud.Project;
29 import org.sonar.alm.client.bitbucket.bitbucketcloud.Repository;
30 import org.sonar.api.server.ws.WebService;
31 import org.sonar.api.utils.System2;
32 import org.sonar.core.i18n.I18n;
33 import org.sonar.core.util.SequenceUuidFactory;
34 import org.sonar.db.DbTester;
35 import org.sonar.db.alm.pat.AlmPatDto;
36 import org.sonar.db.alm.setting.AlmSettingDto;
37 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
38 import org.sonar.db.component.BranchDto;
39 import org.sonar.db.project.ProjectDto;
40 import org.sonar.db.user.UserDto;
41 import org.sonar.server.almintegration.ws.ImportHelper;
42 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
43 import org.sonar.server.component.ComponentUpdater;
44 import org.sonar.server.es.TestProjectIndexers;
45 import org.sonar.server.exceptions.BadRequestException;
46 import org.sonar.server.exceptions.ForbiddenException;
47 import org.sonar.server.exceptions.NotFoundException;
48 import org.sonar.server.exceptions.UnauthorizedException;
49 import org.sonar.server.favorite.FavoriteUpdater;
50 import org.sonar.server.permission.PermissionTemplateService;
51 import org.sonar.server.project.ProjectDefaultVisibility;
52 import org.sonar.server.project.Visibility;
53 import org.sonar.server.tester.UserSessionRule;
54 import org.sonar.server.ws.TestRequest;
55 import org.sonar.server.ws.WsActionTester;
56 import org.sonarqube.ws.Projects;
57
58 import static java.util.Objects.requireNonNull;
59 import static org.assertj.core.api.Assertions.assertThat;
60 import static org.assertj.core.api.Assertions.assertThatThrownBy;
61 import static org.assertj.core.api.Assertions.tuple;
62 import static org.mockito.ArgumentMatchers.any;
63 import static org.mockito.Mockito.mock;
64 import static org.mockito.Mockito.verify;
65 import static org.mockito.Mockito.when;
66 import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto;
67 import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS;
68 import static org.sonar.db.permission.GlobalPermission.SCAN;
69
70 public class ImportBitbucketCloudRepoActionTest {
71
72   private static final String GENERATED_PROJECT_KEY = "TEST_PROJECT_KEY";
73
74   @Rule
75   public UserSessionRule userSession = UserSessionRule.standalone();
76   @Rule
77   public DbTester db = DbTester.create();
78
79   private final ProjectDefaultVisibility projectDefaultVisibility = mock(ProjectDefaultVisibility.class);
80   private final BitbucketCloudRestClient bitbucketCloudRestClient = mock(BitbucketCloudRestClient.class);
81
82   private final ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), mock(I18n.class), System2.INSTANCE,
83     mock(PermissionTemplateService.class), new FavoriteUpdater(db.getDbClient()), new TestProjectIndexers(), new SequenceUuidFactory());
84
85   private final ImportHelper importHelper = new ImportHelper(db.getDbClient(), userSession);
86   private final ProjectKeyGenerator projectKeyGenerator = mock(ProjectKeyGenerator.class);
87   private final WsActionTester ws = new WsActionTester(new ImportBitbucketCloudRepoAction(db.getDbClient(), userSession,
88     bitbucketCloudRestClient, projectDefaultVisibility, componentUpdater, importHelper, projectKeyGenerator));
89
90   @Before
91   public void before() {
92     when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE);
93     when(projectKeyGenerator.generateUniqueProjectKey(any(), any())).thenReturn(GENERATED_PROJECT_KEY);
94   }
95
96   @Test
97   public void import_project() {
98     UserDto user = db.users().insertUser();
99     userSession.logIn(user).addPermission(PROVISION_PROJECTS);
100     AlmSettingDto almSetting = db.almSettings().insertBitbucketCloudAlmSetting();
101     db.almPats().insert(dto -> {
102       dto.setAlmSettingUuid(almSetting.getUuid());
103       dto.setUserUuid(user.getUuid());
104     });
105     Repository repo = getGsonBBCRepo();
106     when(bitbucketCloudRestClient.getRepo(any(), any(), any())).thenReturn(repo);
107
108     Projects.CreateWsResponse response = ws.newRequest()
109       .setParam("almSetting", almSetting.getKey())
110       .setParam("repositorySlug", "repo-slug-1")
111       .executeProtobuf(Projects.CreateWsResponse.class);
112
113     Projects.CreateWsResponse.Project result = response.getProject();
114     assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY);
115     assertThat(result.getName()).isEqualTo(repo.getName());
116
117     Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
118     assertThat(projectDto).isPresent();
119     Optional<ProjectAlmSettingDto> projectAlmSettingDto = db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get());
120     assertThat(projectAlmSettingDto).isPresent();
121     assertThat(projectAlmSettingDto.get().getAlmRepo()).isEqualTo("repo-slug-1");
122
123     Optional<BranchDto> branchDto = db.getDbClient().branchDao().selectByBranchKey(db.getSession(), projectDto.get().getUuid(), "develop");
124     assertThat(branchDto).isPresent();
125     assertThat(branchDto.get().isMain()).isTrue();
126     verify(projectKeyGenerator).generateUniqueProjectKey(requireNonNull(almSetting.getAppId()), repo.getSlug());
127   }
128
129   @Test
130   public void fail_project_already_exist() {
131     UserDto user = db.users().insertUser();
132     userSession.logIn(user).addPermission(PROVISION_PROJECTS);
133     AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting();
134     db.almPats().insert(dto -> {
135       dto.setAlmSettingUuid(almSetting.getUuid());
136       dto.setUserUuid(user.getUuid());
137     });
138     Repository repo = getGsonBBCRepo();
139     db.components().insertPublicProject(p -> p.setDbKey(GENERATED_PROJECT_KEY));
140
141     when(bitbucketCloudRestClient.getRepo(any(), any(), any())).thenReturn(repo);
142
143     TestRequest request = ws.newRequest()
144       .setParam("almSetting", almSetting.getKey())
145       .setParam("repositorySlug", "repo-slug-1");
146
147     assertThatThrownBy(request::execute)
148       .isInstanceOf(BadRequestException.class)
149       .hasMessageContaining("Could not create null, key already exists: " + GENERATED_PROJECT_KEY);
150   }
151
152   @Test
153   public void fail_when_not_logged_in() {
154     TestRequest request = ws.newRequest()
155       .setParam("almSetting", "sdgfdshfjztutz")
156       .setParam("projectKey", "projectKey")
157       .setParam("repositorySlug", "repo-slug");
158
159     assertThatThrownBy(request::execute)
160       .isInstanceOf(UnauthorizedException.class);
161   }
162
163   @Test
164   public void fail_when_missing_project_creator_permission() {
165     UserDto user = db.users().insertUser();
166     userSession.logIn(user).addPermission(SCAN);
167
168     TestRequest request = ws.newRequest()
169       .setParam("almSetting", "sdgfdshfjztutz")
170       .setParam("projectKey", "projectKey")
171       .setParam("repositorySlug", "repo-slug");
172
173     assertThatThrownBy(request::execute)
174       .isInstanceOf(ForbiddenException.class)
175       .hasMessageContaining("Insufficient privileges");
176   }
177
178   @Test
179   public void check_pat_is_missing() {
180     UserDto user = db.users().insertUser();
181     userSession.logIn(user).addPermission(PROVISION_PROJECTS);
182     AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting();
183
184     TestRequest request = ws.newRequest()
185       .setParam("almSetting", almSetting.getKey())
186       .setParam("repositorySlug", "repo");
187
188     assertThatThrownBy(request::execute)
189       .isInstanceOf(IllegalArgumentException.class)
190       .hasMessageContaining("Username and App Password for '" + almSetting.getKey() + "' is missing");
191   }
192
193   @Test
194   public void fail_check_alm_setting_not_found() {
195     UserDto user = db.users().insertUser();
196     userSession.logIn(user).addPermission(PROVISION_PROJECTS);
197     AlmPatDto almPatDto = newAlmPatDto();
198     db.getDbClient().almPatDao().insert(db.getSession(), almPatDto, user.getLogin(), null);
199
200     TestRequest request = ws.newRequest()
201       .setParam("almSetting", "testKey")
202       .setParam("repositorySlug", "repo");
203
204     assertThatThrownBy(request::execute)
205       .isInstanceOf(NotFoundException.class)
206       .hasMessageContaining("ALM Setting 'testKey' not found");
207   }
208
209   @Test
210   public void fail_when_no_creation_project_permission() {
211     UserDto user = db.users().insertUser();
212     userSession.logIn(user);
213
214     TestRequest request = ws.newRequest()
215       .setParam("almSetting", "anyvalue");
216
217     assertThatThrownBy(request::execute)
218       .isInstanceOf(ForbiddenException.class)
219       .hasMessageContaining("Insufficient privileges");
220   }
221
222   @Test
223   public void definition() {
224     WebService.Action def = ws.getDef();
225
226     assertThat(def.since()).isEqualTo("9.0");
227     assertThat(def.isPost()).isTrue();
228     assertThat(def.params())
229       .extracting(WebService.Param::key, WebService.Param::isRequired)
230       .containsExactlyInAnyOrder(
231         tuple("almSetting", true),
232         tuple("repositorySlug", true));
233   }
234
235   private Repository getGsonBBCRepo() {
236     Project project1 = new Project("PROJECT-UUID-ONE", "projectKey1", "projectName1");
237     MainBranch mainBranch = new MainBranch("branch", "develop");
238     return new Repository("REPO-UUID-ONE", "repo-slug-1", "repoName1", project1, mainBranch);
239   }
240
241 }