]> source.dussan.org Git - sonarqube.git/blob
22b2439e19778c94da0dbed6a6b6dc59c5a197e5
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2021 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 java.util.stream.IntStream;
24
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;
56
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;
67
68 public class ImportAzureProjectActionTest {
69
70   @Rule
71   public UserSessionRule userSession = UserSessionRule.standalone();
72   @Rule
73   public DbTester db = DbTester.create();
74
75   private final AzureDevOpsHttpClient azureDevOpsHttpClient = mock(AzureDevOpsHttpClient.class);
76
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());
79
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);
85
86   @Before
87   public void before() {
88     when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE);
89   }
90
91   @Test
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());
100     });
101     GsonAzureRepo repo = getGsonAzureRepo();
102     when(azureDevOpsHttpClient.getRepo(almSetting.getUrl(), almSetting.getPersonalAccessToken(), "project-name", "repo-name"))
103       .thenReturn(repo);
104
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);
110
111     Projects.CreateWsResponse.Project result = response.getProject();
112     assertThat(result.getKey()).isEqualTo(repo.getProject().getName() + "_" + repo.getName());
113     assertThat(result.getName()).isEqualTo(repo.getName());
114
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");
121   }
122
123   @Test
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");
129
130     assertThatThrownBy(() -> request.execute())
131       .isInstanceOf(UnauthorizedException.class);
132   }
133
134   @Test
135   public void fail_when_missing_project_creator_permission() {
136     UserDto user = db.users().insertUser();
137     userSession.logIn(user).addPermission(SCAN);
138
139     TestRequest request = ws.newRequest()
140       .setParam("almSetting", "azure")
141       .setParam("projectName", "project-name")
142       .setParam("repositoryName", "repo-name");
143
144     assertThatThrownBy(() -> request.execute())
145       .isInstanceOf(ForbiddenException.class)
146       .hasMessage("Insufficient privileges");
147   }
148
149   @Test
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();
154
155     TestRequest request = ws.newRequest()
156       .setParam("almSetting", almSetting.getKey())
157       .setParam("projectName", "project-name")
158       .setParam("repositoryName", "repo-name");
159
160     assertThatThrownBy(() -> request.execute())
161       .isInstanceOf(IllegalArgumentException.class)
162       .hasMessage("personal access token for '" + almSetting.getKey() + "' is missing");
163   }
164
165   @Test
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);
171
172     TestRequest request = ws.newRequest()
173       .setParam("almSetting", "testKey");
174
175     assertThatThrownBy(() -> request.execute())
176       .isInstanceOf(NotFoundException.class)
177       .hasMessage("ALM Setting 'testKey' not found");
178   }
179
180   @Test
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());
189     });
190     GsonAzureRepo repo = getGsonAzureRepo();
191     String projectKey = repo.getProject().getName() + "_" + repo.getName();
192     db.components().insertPublicProject(p -> p.setDbKey(projectKey));
193
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");
199
200     assertThatThrownBy(() -> request.execute())
201       .isInstanceOf(BadRequestException.class)
202       .hasMessage("Could not create null, key already exists: " + projectKey);
203   }
204
205   @Test
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");
209   }
210
211   @Test
212   public void sanitize_long_project_and_repo_names() {
213     String projectName = IntStream.range(0, 260).mapToObj(i -> "a").collect(joining());
214
215     assertThat(importAzureProjectAction.generateProjectKey(projectName, "repo name"))
216       .hasSize(250);
217   }
218
219   @Test
220   public void define() {
221     WebService.Action def = ws.getDef();
222
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));
231   }
232
233   private GsonAzureRepo getGsonAzureRepo() {
234     return new GsonAzureRepo("repo-id", "repo-name", "repo-url",
235       new GsonAzureProject("project-name", "project-description"));
236   }
237
238 }