]> source.dussan.org Git - sonarqube.git/blob
6b5d25f5ca82da5eb39bc479fa43dc406aed03f2
[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.azure;
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.azure.AzureDevOpsHttpClient;
27 import org.sonar.alm.client.azure.GsonAzureProject;
28 import org.sonar.alm.client.azure.GsonAzureRepo;
29 import org.sonar.api.config.internal.Encryption;
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 org.assertj.core.api.Assertions.assertThat;
59 import static org.assertj.core.api.Assertions.assertThatThrownBy;
60 import static org.assertj.core.api.Assertions.tuple;
61 import static org.mockito.ArgumentMatchers.any;
62 import static org.mockito.Mockito.mock;
63 import static org.mockito.Mockito.verify;
64 import static org.mockito.Mockito.when;
65 import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto;
66 import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS;
67 import static org.sonar.db.permission.GlobalPermission.SCAN;
68
69 public class ImportAzureProjectActionTest {
70
71   private static final String GENERATED_PROJECT_KEY = "TEST_PROJECT_KEY";
72
73   @Rule
74   public UserSessionRule userSession = UserSessionRule.standalone();
75   @Rule
76   public DbTester db = DbTester.create();
77
78   private final AzureDevOpsHttpClient azureDevOpsHttpClient = mock(AzureDevOpsHttpClient.class);
79
80   private final ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), mock(I18n.class), System2.INSTANCE,
81     mock(PermissionTemplateService.class), new FavoriteUpdater(db.getDbClient()), new TestProjectIndexers(), new SequenceUuidFactory());
82
83   private final Encryption encryption = mock(Encryption.class);
84   private final ImportHelper importHelper = new ImportHelper(db.getDbClient(), userSession);
85   private final ProjectDefaultVisibility projectDefaultVisibility = mock(ProjectDefaultVisibility.class);
86   private final ProjectKeyGenerator projectKeyGenerator = mock(ProjectKeyGenerator.class);
87   private final ImportAzureProjectAction importAzureProjectAction = new ImportAzureProjectAction(db.getDbClient(), userSession,
88     azureDevOpsHttpClient, projectDefaultVisibility, componentUpdater, importHelper, projectKeyGenerator);
89   private final WsActionTester ws = new WsActionTester(importAzureProjectAction);
90
91   @Before
92   public void before() {
93     when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE);
94     when(projectKeyGenerator.generateUniqueProjectKey(any(), any())).thenReturn(GENERATED_PROJECT_KEY);
95   }
96
97   @Test
98   public void import_project() {
99     UserDto user = db.users().insertUser();
100     userSession.logIn(user).addPermission(PROVISION_PROJECTS);
101     AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting();
102     db.almPats().insert(dto -> {
103       dto.setAlmSettingUuid(almSetting.getUuid());
104       dto.setPersonalAccessToken(almSetting.getDecryptedPersonalAccessToken(encryption));
105       dto.setUserUuid(user.getUuid());
106     });
107     GsonAzureRepo repo = getGsonAzureRepo();
108     when(azureDevOpsHttpClient.getRepo(almSetting.getUrl(), almSetting.getDecryptedPersonalAccessToken(encryption),
109       "project-name", "repo-name"))
110       .thenReturn(repo);
111
112     Projects.CreateWsResponse response = ws.newRequest()
113       .setParam("almSetting", almSetting.getKey())
114       .setParam("projectName", "project-name")
115       .setParam("repositoryName", "repo-name")
116       .executeProtobuf(Projects.CreateWsResponse.class);
117
118     Projects.CreateWsResponse.Project result = response.getProject();
119     assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY);
120     assertThat(result.getName()).isEqualTo(repo.getName());
121
122     Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
123     assertThat(projectDto).isPresent();
124
125     Optional<ProjectAlmSettingDto> projectAlmSettingDto = db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get());
126     assertThat(projectAlmSettingDto.get().getAlmRepo()).isEqualTo("repo-name");
127     assertThat(projectAlmSettingDto.get().getAlmSettingUuid()).isEqualTo(almSetting.getUuid());
128     assertThat(projectAlmSettingDto.get().getAlmSlug()).isEqualTo("project-name");
129
130     Optional<BranchDto> mainBranch = db.getDbClient()
131       .branchDao()
132       .selectByProject(db.getSession(), projectDto.get())
133       .stream()
134       .filter(BranchDto::isMain)
135       .findFirst();
136     assertThat(mainBranch).isPresent();
137     assertThat(mainBranch.get().getKey()).hasToString("repo-default-branch");
138
139     verify(projectKeyGenerator).generateUniqueProjectKey(repo.getProject().getName(), repo.getName());
140   }
141
142   @Test
143   public void import_project_from_empty_repo() {
144     UserDto user = db.users().insertUser();
145     userSession.logIn(user).addPermission(PROVISION_PROJECTS);
146     AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting();
147     db.almPats().insert(dto -> {
148       dto.setAlmSettingUuid(almSetting.getUuid());
149       dto.setPersonalAccessToken(almSetting.getDecryptedPersonalAccessToken(encryption));
150       dto.setUserUuid(user.getUuid());
151     });
152     GsonAzureRepo repo = getEmptyGsonAzureRepo();
153     when(azureDevOpsHttpClient.getRepo(almSetting.getUrl(), almSetting.getDecryptedPersonalAccessToken(encryption),
154       "project-name", "repo-name"))
155       .thenReturn(repo);
156
157     Projects.CreateWsResponse response = ws.newRequest()
158       .setParam("almSetting", almSetting.getKey())
159       .setParam("projectName", "project-name")
160       .setParam("repositoryName", "repo-name")
161       .executeProtobuf(Projects.CreateWsResponse.class);
162
163     Projects.CreateWsResponse.Project result = response.getProject();
164     Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
165     Optional<BranchDto> mainBranch = db.getDbClient()
166       .branchDao()
167       .selectByProject(db.getSession(), projectDto.get())
168       .stream()
169       .filter(BranchDto::isMain)
170       .findFirst();
171
172     assertThat(mainBranch).isPresent();
173     assertThat(mainBranch.get().getKey()).hasToString("master");
174   }
175
176   @Test
177   public void fail_when_not_logged_in() {
178     TestRequest request = ws.newRequest()
179       .setParam("almSetting", "azure")
180       .setParam("projectName", "project-name")
181       .setParam("repositoryName", "repo-name");
182
183     assertThatThrownBy(() -> request.execute())
184       .isInstanceOf(UnauthorizedException.class);
185   }
186
187   @Test
188   public void fail_when_missing_project_creator_permission() {
189     UserDto user = db.users().insertUser();
190     userSession.logIn(user).addPermission(SCAN);
191
192     TestRequest request = ws.newRequest()
193       .setParam("almSetting", "azure")
194       .setParam("projectName", "project-name")
195       .setParam("repositoryName", "repo-name");
196
197     assertThatThrownBy(request::execute)
198       .isInstanceOf(ForbiddenException.class)
199       .hasMessage("Insufficient privileges");
200   }
201
202   @Test
203   public void check_pat_is_missing() {
204     UserDto user = db.users().insertUser();
205     userSession.logIn(user).addPermission(PROVISION_PROJECTS);
206     AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting();
207
208     TestRequest request = ws.newRequest()
209       .setParam("almSetting", almSetting.getKey())
210       .setParam("projectName", "project-name")
211       .setParam("repositoryName", "repo-name");
212
213     assertThatThrownBy(request::execute)
214       .isInstanceOf(IllegalArgumentException.class)
215       .hasMessage("personal access token for '" + almSetting.getKey() + "' is missing");
216   }
217
218   @Test
219   public void fail_check_alm_setting_not_found() {
220     UserDto user = db.users().insertUser();
221     userSession.logIn(user).addPermission(PROVISION_PROJECTS);
222     AlmPatDto almPatDto = newAlmPatDto();
223     db.getDbClient().almPatDao().insert(db.getSession(), almPatDto, user.getLogin(), null);
224
225     TestRequest request = ws.newRequest()
226       .setParam("almSetting", "testKey");
227
228     assertThatThrownBy(request::execute)
229       .isInstanceOf(NotFoundException.class)
230       .hasMessage("ALM Setting 'testKey' not found");
231   }
232
233   @Test
234   public void fail_project_already_exists() {
235     UserDto user = db.users().insertUser();
236     userSession.logIn(user).addPermission(PROVISION_PROJECTS);
237     AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting();
238     db.almPats().insert(dto -> {
239       dto.setAlmSettingUuid(almSetting.getUuid());
240       dto.setPersonalAccessToken(almSetting.getDecryptedPersonalAccessToken(encryption));
241       dto.setUserUuid(user.getUuid());
242     });
243     GsonAzureRepo repo = getGsonAzureRepo();
244     db.components().insertPublicProject(p -> p.setDbKey(GENERATED_PROJECT_KEY));
245
246     when(azureDevOpsHttpClient.getRepo(almSetting.getUrl(), almSetting.getDecryptedPersonalAccessToken(encryption),
247       "project-name", "repo-name")).thenReturn(repo);
248     TestRequest request = ws.newRequest()
249       .setParam("almSetting", almSetting.getKey())
250       .setParam("projectName", "project-name")
251       .setParam("repositoryName", "repo-name");
252
253     assertThatThrownBy(request::execute)
254       .isInstanceOf(BadRequestException.class)
255       .hasMessage("Could not create null, key already exists: " + GENERATED_PROJECT_KEY);
256   }
257
258   @Test
259   public void define() {
260     WebService.Action def = ws.getDef();
261
262     assertThat(def.since()).isEqualTo("8.6");
263     assertThat(def.isPost()).isTrue();
264     assertThat(def.params())
265       .extracting(WebService.Param::key, WebService.Param::isRequired)
266       .containsExactlyInAnyOrder(
267         tuple("almSetting", true),
268         tuple("projectName", true),
269         tuple("repositoryName", true));
270   }
271
272   private GsonAzureRepo getGsonAzureRepo() {
273     return new GsonAzureRepo("repo-id", "repo-name", "repo-url",
274       new GsonAzureProject("project-name", "project-description"),
275       "refs/heads/repo-default-branch");
276   }
277
278   private GsonAzureRepo getEmptyGsonAzureRepo() {
279     return new GsonAzureRepo("repo-id", "repo-name", "repo-url",
280       new GsonAzureProject("project-name", "project-description"), null);
281   }
282
283 }