3 * Copyright (C) 2009-2021 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 java.util.stream.IntStream;
25 import org.junit.Before;
26 import org.junit.Rule;
27 import org.junit.Test;
28 import org.sonar.alm.client.azure.AzureDevOpsHttpClient;
29 import org.sonar.alm.client.azure.GsonAzureProject;
30 import org.sonar.alm.client.azure.GsonAzureRepo;
31 import org.sonar.api.server.ws.WebService;
32 import org.sonar.api.utils.System2;
33 import org.sonar.core.i18n.I18n;
34 import org.sonar.core.util.SequenceUuidFactory;
35 import org.sonar.db.DbTester;
36 import org.sonar.db.alm.pat.AlmPatDto;
37 import org.sonar.db.alm.setting.AlmSettingDto;
38 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
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.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.permission.PermissionTemplateService;
50 import org.sonar.server.project.ProjectDefaultVisibility;
51 import org.sonar.server.project.Visibility;
52 import org.sonar.server.tester.UserSessionRule;
53 import org.sonar.server.ws.TestRequest;
54 import org.sonar.server.ws.WsActionTester;
55 import org.sonarqube.ws.Projects;
57 import static java.util.stream.Collectors.joining;
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.when;
64 import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto;
65 import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS;
66 import static org.sonar.db.permission.GlobalPermission.SCAN;
68 public class ImportAzureProjectActionTest {
71 public UserSessionRule userSession = UserSessionRule.standalone();
73 public DbTester db = DbTester.create();
75 private final AzureDevOpsHttpClient azureDevOpsHttpClient = mock(AzureDevOpsHttpClient.class);
77 private final ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), mock(I18n.class), System2.INSTANCE,
78 mock(PermissionTemplateService.class), new FavoriteUpdater(db.getDbClient()), new TestProjectIndexers(), new SequenceUuidFactory());
80 private final ImportHelper importHelper = new ImportHelper(db.getDbClient(), userSession);
81 private final ProjectDefaultVisibility projectDefaultVisibility = mock(ProjectDefaultVisibility.class);
82 private final ImportAzureProjectAction importAzureProjectAction = new ImportAzureProjectAction(db.getDbClient(), userSession,
83 azureDevOpsHttpClient, projectDefaultVisibility, componentUpdater, importHelper);
84 private final WsActionTester ws = new WsActionTester(importAzureProjectAction);
87 public void before() {
88 when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE);
92 public void import_project() {
93 UserDto user = db.users().insertUser();
94 userSession.logIn(user).addPermission(PROVISION_PROJECTS);
95 AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting();
96 db.almPats().insert(dto -> {
97 dto.setAlmSettingUuid(almSetting.getUuid());
98 dto.setPersonalAccessToken(almSetting.getPersonalAccessToken());
99 dto.setUserUuid(user.getUuid());
101 GsonAzureRepo repo = getGsonAzureRepo();
102 when(azureDevOpsHttpClient.getRepo(almSetting.getUrl(), almSetting.getPersonalAccessToken(), "project-name", "repo-name"))
105 Projects.CreateWsResponse response = ws.newRequest()
106 .setParam("almSetting", almSetting.getKey())
107 .setParam("projectName", "project-name")
108 .setParam("repositoryName", "repo-name")
109 .executeProtobuf(Projects.CreateWsResponse.class);
111 Projects.CreateWsResponse.Project result = response.getProject();
112 assertThat(result.getKey()).isEqualTo(repo.getProject().getName() + "_" + repo.getName());
113 assertThat(result.getName()).isEqualTo(repo.getName());
115 Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
116 assertThat(projectDto).isPresent();
117 Optional<ProjectAlmSettingDto> projectAlmSettingDto = db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get());
118 assertThat(projectAlmSettingDto.get().getAlmRepo()).isEqualTo("repo-name");
119 assertThat(projectAlmSettingDto.get().getAlmSettingUuid()).isEqualTo(almSetting.getUuid());
120 assertThat(projectAlmSettingDto.get().getAlmSlug()).isEqualTo("project-name");
124 public void fail_when_not_logged_in() {
125 TestRequest request = ws.newRequest()
126 .setParam("almSetting", "azure")
127 .setParam("projectName", "project-name")
128 .setParam("repositoryName", "repo-name");
130 assertThatThrownBy(() -> request.execute())
131 .isInstanceOf(UnauthorizedException.class);
135 public void fail_when_missing_project_creator_permission() {
136 UserDto user = db.users().insertUser();
137 userSession.logIn(user).addPermission(SCAN);
139 TestRequest request = ws.newRequest()
140 .setParam("almSetting", "azure")
141 .setParam("projectName", "project-name")
142 .setParam("repositoryName", "repo-name");
144 assertThatThrownBy(() -> request.execute())
145 .isInstanceOf(ForbiddenException.class)
146 .hasMessage("Insufficient privileges");
150 public void check_pat_is_missing() {
151 UserDto user = db.users().insertUser();
152 userSession.logIn(user).addPermission(PROVISION_PROJECTS);
153 AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting();
155 TestRequest request = ws.newRequest()
156 .setParam("almSetting", almSetting.getKey())
157 .setParam("projectName", "project-name")
158 .setParam("repositoryName", "repo-name");
160 assertThatThrownBy(() -> request.execute())
161 .isInstanceOf(IllegalArgumentException.class)
162 .hasMessage("personal access token for '" + almSetting.getKey() + "' is missing");
166 public void fail_check_alm_setting_not_found() {
167 UserDto user = db.users().insertUser();
168 userSession.logIn(user).addPermission(PROVISION_PROJECTS);
169 AlmPatDto almPatDto = newAlmPatDto();
170 db.getDbClient().almPatDao().insert(db.getSession(), almPatDto);
172 TestRequest request = ws.newRequest()
173 .setParam("almSetting", "testKey");
175 assertThatThrownBy(() -> request.execute())
176 .isInstanceOf(NotFoundException.class)
177 .hasMessage("ALM Setting 'testKey' not found");
181 public void fail_project_already_exists() {
182 UserDto user = db.users().insertUser();
183 userSession.logIn(user).addPermission(PROVISION_PROJECTS);
184 AlmSettingDto almSetting = db.almSettings().insertAzureAlmSetting();
185 db.almPats().insert(dto -> {
186 dto.setAlmSettingUuid(almSetting.getUuid());
187 dto.setPersonalAccessToken(almSetting.getPersonalAccessToken());
188 dto.setUserUuid(user.getUuid());
190 GsonAzureRepo repo = getGsonAzureRepo();
191 String projectKey = repo.getProject().getName() + "_" + repo.getName();
192 db.components().insertPublicProject(p -> p.setDbKey(projectKey));
194 when(azureDevOpsHttpClient.getRepo(almSetting.getUrl(), almSetting.getPersonalAccessToken(), "project-name", "repo-name")).thenReturn(repo);
195 TestRequest request = ws.newRequest()
196 .setParam("almSetting", almSetting.getKey())
197 .setParam("projectName", "project-name")
198 .setParam("repositoryName", "repo-name");
200 assertThatThrownBy(() -> request.execute())
201 .isInstanceOf(BadRequestException.class)
202 .hasMessage("Could not create null, key already exists: " + projectKey);
206 public void sanitize_project_and_repo_names_with_invalid_characters() {
207 assertThat(importAzureProjectAction.generateProjectKey("project name", "repo name"))
208 .isEqualTo("project_name_repo_name");
212 public void sanitize_long_project_and_repo_names() {
213 String projectName = IntStream.range(0, 260).mapToObj(i -> "a").collect(joining());
215 assertThat(importAzureProjectAction.generateProjectKey(projectName, "repo name"))
220 public void define() {
221 WebService.Action def = ws.getDef();
223 assertThat(def.since()).isEqualTo("8.6");
224 assertThat(def.isPost()).isTrue();
225 assertThat(def.params())
226 .extracting(WebService.Param::key, WebService.Param::isRequired)
227 .containsExactlyInAnyOrder(
228 tuple("almSetting", true),
229 tuple("projectName", true),
230 tuple("repositoryName", true));
233 private GsonAzureRepo getGsonAzureRepo() {
234 return new GsonAzureRepo("repo-id", "repo-name", "repo-url",
235 new GsonAzureProject("project-name", "project-description"));