3 * Copyright (C) 2009-2022 SonarSource SA
4 * mailto:info AT sonarsource DOT com
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.
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.
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.
20 package org.sonar.server.almintegration.ws.azure;
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;
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;
69 public class ImportAzureProjectActionTest {
71 private static final String GENERATED_PROJECT_KEY = "TEST_PROJECT_KEY";
74 public UserSessionRule userSession = UserSessionRule.standalone();
76 public DbTester db = DbTester.create();
78 public final I18nRule i18n = new I18nRule();
80 private final AzureDevOpsHttpClient azureDevOpsHttpClient = mock(AzureDevOpsHttpClient.class);
82 private final ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), i18n, System2.INSTANCE,
83 mock(PermissionTemplateService.class), new FavoriteUpdater(db.getDbClient()), new TestProjectIndexers(), new SequenceUuidFactory());
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);
94 public void before() {
95 when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE);
96 when(projectKeyGenerator.generateUniqueProjectKey(any(), any())).thenReturn(GENERATED_PROJECT_KEY);
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());
109 GsonAzureRepo repo = getGsonAzureRepo();
110 when(azureDevOpsHttpClient.getRepo(almSetting.getUrl(), almSetting.getDecryptedPersonalAccessToken(encryption),
111 "project-name", "repo-name"))
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);
120 Projects.CreateWsResponse.Project result = response.getProject();
121 assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY);
122 assertThat(result.getName()).isEqualTo(repo.getName());
124 Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
125 assertThat(projectDto).isPresent();
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");
132 Optional<BranchDto> mainBranch = db.getDbClient()
134 .selectByProject(db.getSession(), projectDto.get())
136 .filter(BranchDto::isMain)
138 assertThat(mainBranch).isPresent();
139 assertThat(mainBranch.get().getKey()).hasToString("repo-default-branch");
141 verify(projectKeyGenerator).generateUniqueProjectKey(repo.getProject().getName(), repo.getName());
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());
154 GsonAzureRepo repo = getEmptyGsonAzureRepo();
155 when(azureDevOpsHttpClient.getRepo(almSetting.getUrl(), almSetting.getDecryptedPersonalAccessToken(encryption),
156 "project-name", "repo-name"))
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);
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()
169 .selectByProject(db.getSession(), projectDto.get())
171 .filter(BranchDto::isMain)
174 assertThat(mainBranch).isPresent();
175 assertThat(mainBranch.get().getKey()).hasToString("master");
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");
185 assertThatThrownBy(() -> request.execute())
186 .isInstanceOf(UnauthorizedException.class);
190 public void fail_when_missing_project_creator_permission() {
191 UserDto user = db.users().insertUser();
192 userSession.logIn(user).addPermission(SCAN);
194 TestRequest request = ws.newRequest()
195 .setParam("almSetting", "azure")
196 .setParam("projectName", "project-name")
197 .setParam("repositoryName", "repo-name");
199 assertThatThrownBy(request::execute)
200 .isInstanceOf(ForbiddenException.class)
201 .hasMessage("Insufficient privileges");
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();
210 TestRequest request = ws.newRequest()
211 .setParam("almSetting", almSetting.getKey())
212 .setParam("projectName", "project-name")
213 .setParam("repositoryName", "repo-name");
215 assertThatThrownBy(request::execute)
216 .isInstanceOf(IllegalArgumentException.class)
217 .hasMessage("personal access token for '" + almSetting.getKey() + "' is missing");
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);
227 TestRequest request = ws.newRequest()
228 .setParam("almSetting", "testKey");
230 assertThatThrownBy(request::execute)
231 .isInstanceOf(NotFoundException.class)
232 .hasMessage("ALM Setting 'testKey' not found");
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());
245 GsonAzureRepo repo = getGsonAzureRepo();
246 db.components().insertPublicProject(p -> p.setDbKey(GENERATED_PROJECT_KEY));
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");
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);
261 public void define() {
262 WebService.Action def = ws.getDef();
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));
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");
280 private GsonAzureRepo getEmptyGsonAzureRepo() {
281 return new GsonAzureRepo("repo-id", "repo-name", "repo-url",
282 new GsonAzureProject("project-name", "project-description"), null);