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