]> source.dussan.org Git - sonarqube.git/blob
dcff559a270125997f7f1271f494b26939118362
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2024 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.common.almsettings.github;
21
22 import java.util.Arrays;
23 import java.util.Collection;
24 import java.util.Optional;
25 import java.util.Set;
26 import org.junit.jupiter.api.BeforeEach;
27 import org.junit.jupiter.api.Test;
28 import org.junit.jupiter.api.extension.ExtendWith;
29 import org.mockito.Answers;
30 import org.mockito.ArgumentCaptor;
31 import org.mockito.Captor;
32 import org.mockito.Mock;
33 import org.mockito.junit.jupiter.MockitoExtension;
34 import org.sonar.alm.client.github.GithubPermissionConverter;
35 import org.sonar.api.resources.Qualifiers;
36 import org.sonar.api.web.UserRole;
37 import org.sonar.auth.github.AppInstallationToken;
38 import org.sonar.auth.github.GitHubSettings;
39 import org.sonar.auth.github.GsonRepositoryCollaborator;
40 import org.sonar.auth.github.GsonRepositoryPermissions;
41 import org.sonar.auth.github.GsonRepositoryTeam;
42 import org.sonar.auth.github.client.GithubApplicationClient;
43 import org.sonar.auth.github.security.AccessToken;
44 import org.sonar.db.DbClient;
45 import org.sonar.db.alm.setting.ALM;
46 import org.sonar.db.alm.setting.AlmSettingDto;
47 import org.sonar.db.alm.setting.ProjectAlmSettingDao;
48 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
49 import org.sonar.db.component.BranchDto;
50 import org.sonar.db.project.CreationMethod;
51 import org.sonar.db.project.ProjectDto;
52 import org.sonar.db.provisioning.GithubPermissionsMappingDto;
53 import org.sonar.db.user.GroupDto;
54 import org.sonar.server.common.almintegration.ProjectKeyGenerator;
55 import org.sonar.server.common.almsettings.DevOpsProjectDescriptor;
56 import org.sonar.server.common.component.ComponentCreationParameters;
57 import org.sonar.server.common.component.ComponentUpdater;
58 import org.sonar.server.common.component.NewComponent;
59 import org.sonar.server.common.permission.PermissionUpdater;
60 import org.sonar.server.common.permission.UserPermissionChange;
61 import org.sonar.server.common.project.ProjectCreator;
62 import org.sonar.server.component.ComponentCreationData;
63 import org.sonar.server.management.ManagedProjectService;
64 import org.sonar.server.permission.PermissionService;
65 import org.sonar.server.permission.PermissionServiceImpl;
66 import org.sonar.server.project.ProjectDefaultVisibility;
67 import org.sonar.server.project.Visibility;
68 import org.sonar.server.user.UserSession;
69
70 import static java.util.Objects.requireNonNull;
71 import static java.util.stream.Collectors.toSet;
72 import static org.assertj.core.api.Assertions.assertThat;
73 import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
74 import static org.mockito.ArgumentMatchers.any;
75 import static org.mockito.ArgumentMatchers.eq;
76 import static org.mockito.Mockito.lenient;
77 import static org.mockito.Mockito.mock;
78 import static org.mockito.Mockito.verify;
79 import static org.mockito.Mockito.when;
80 import static org.sonar.db.project.CreationMethod.ALM_IMPORT_API;
81 import static org.sonar.db.project.CreationMethod.SCANNER_API_DEVOPS_AUTO_CONFIG;
82
83 @ExtendWith(MockitoExtension.class)
84 class GithubProjectCreatorTest {
85
86   private static final String ORGANIZATION_NAME = "orga2";
87   private static final String REPOSITORY_NAME = "repo1";
88
89   private static final String MAIN_BRANCH_NAME = "defaultBranch";
90   private static final DevOpsProjectDescriptor DEVOPS_PROJECT_DESCRIPTOR = new DevOpsProjectDescriptor(ALM.GITHUB, "http://api.com", ORGANIZATION_NAME + "/" + REPOSITORY_NAME);
91   private static final String ALM_SETTING_KEY = "github_config_1";
92   private static final String USER_LOGIN = "userLogin";
93   private static final String USER_UUID = "userUuid";
94
95   @Mock(answer = Answers.RETURNS_DEEP_STUBS)
96   private DbClient dbClient;
97   @Mock
98   private GithubApplicationClient githubApplicationClient;
99   @Mock
100   private GithubPermissionConverter githubPermissionConverter;
101   @Mock
102   private ProjectKeyGenerator projectKeyGenerator;
103   @Mock
104   private ComponentUpdater componentUpdater;
105   @Mock
106   private GithubProjectCreationParameters githubProjectCreationParameters;
107   @Mock
108   private AccessToken devOpsAppInstallationToken;
109   @Mock
110   private AppInstallationToken authAppInstallationToken;
111   @Mock
112   private UserSession userSession;
113   @Mock
114   private AlmSettingDto almSettingDto;
115   private final PermissionService permissionService = new PermissionServiceImpl(mock());
116   @Mock
117   private PermissionUpdater<UserPermissionChange> permissionUpdater;
118   @Mock
119   private ManagedProjectService managedProjectService;
120   @Mock(answer = Answers.RETURNS_DEEP_STUBS)
121   private ProjectDefaultVisibility projectDefaultVisibility;
122   private final GitHubSettings gitHubSettings = mock();
123
124   private GithubProjectCreator githubProjectCreator;
125
126   @Captor
127   ArgumentCaptor<ComponentCreationParameters> componentCreationParametersCaptor;
128   @Captor
129   ArgumentCaptor<ProjectAlmSettingDto> projectAlmSettingDtoCaptor;
130
131   @BeforeEach
132   void setup() {
133     lenient().when(userSession.getLogin()).thenReturn(USER_LOGIN);
134     lenient().when(userSession.getUuid()).thenReturn(USER_UUID);
135
136     lenient().when(almSettingDto.getUrl()).thenReturn(DEVOPS_PROJECT_DESCRIPTOR.url());
137     lenient().when(almSettingDto.getKey()).thenReturn(ALM_SETTING_KEY);
138
139     when(githubProjectCreationParameters.devOpsProjectDescriptor()).thenReturn(DEVOPS_PROJECT_DESCRIPTOR);
140     when(githubProjectCreationParameters.userSession()).thenReturn(userSession);
141     when(githubProjectCreationParameters.devOpsAppInstallationToken()).thenReturn(devOpsAppInstallationToken);
142     when(githubProjectCreationParameters.authAppInstallationToken()).thenReturn(authAppInstallationToken);
143     when(githubProjectCreationParameters.almSettingDto()).thenReturn(almSettingDto);
144
145     ProjectCreator projectCreator = new ProjectCreator(userSession, projectDefaultVisibility, componentUpdater);
146     githubProjectCreator = new GithubProjectCreator(dbClient, githubApplicationClient, githubPermissionConverter, projectKeyGenerator,
147       permissionUpdater, permissionService, managedProjectService, projectCreator, githubProjectCreationParameters, gitHubSettings);
148
149   }
150
151   @Test
152   void isScanAllowedUsingPermissionsFromDevopsPlatform_whenNoAuthToken_throws() {
153     when(githubProjectCreationParameters.authAppInstallationToken()).thenReturn(null);
154
155     assertThatIllegalStateException().isThrownBy(() -> githubProjectCreator.isScanAllowedUsingPermissionsFromDevopsPlatform())
156       .withMessage("An auth app token is required in case repository permissions checking is necessary.");
157   }
158
159   @Test
160   void isScanAllowedUsingPermissionsFromDevopsPlatform_whenUserIsNotAGitHubUser_returnsFalse() {
161     assertThat(githubProjectCreator.isScanAllowedUsingPermissionsFromDevopsPlatform()).isFalse();
162   }
163
164   @Test
165   void isScanAllowedUsingPermissionsFromDevopsPlatform_whenCollaboratorHasDirectAccessButNoScanPermissions_returnsFalse() {
166     GsonRepositoryCollaborator collaborator1 = mockCollaborator("collaborator1", 1, "role1", "read", "admin");
167     mockGithubCollaboratorsFromApi(collaborator1);
168     bindSessionToCollaborator(collaborator1);
169
170     assertThat(githubProjectCreator.isScanAllowedUsingPermissionsFromDevopsPlatform()).isFalse();
171   }
172
173   @Test
174   void isScanAllowedUsingPermissionsFromDevopsPlatform_whenCollaboratorHasDirectAccess_returnsTrue() {
175     GsonRepositoryCollaborator collaborator1 = mockCollaborator("collaborator1", 1, "role1", "read", "admin");
176     GsonRepositoryCollaborator collaborator2 = mockCollaborator("collaborator2", 2, "role2", "read", "scan");
177     mockGithubCollaboratorsFromApi(collaborator1, collaborator2);
178     bindSessionToCollaborator(collaborator2);
179
180     assertThat(githubProjectCreator.isScanAllowedUsingPermissionsFromDevopsPlatform()).isTrue();
181   }
182
183   @Test
184   void isScanAllowedUsingPermissionsFromDevopsPlatform_whenAccessViaTeamButNoScanPermissions_returnsFalse() {
185     GsonRepositoryTeam team2 = mockGithubTeam("team2", 2, "role2", "another_perm", UserRole.ADMIN);
186     mockTeamsFromApi(team2);
187     bindGroupsToUser(team2.name());
188
189     assertThat(githubProjectCreator.isScanAllowedUsingPermissionsFromDevopsPlatform()).isFalse();
190   }
191
192   @Test
193   void isScanAllowedUsingPermissionsFromDevopsPlatform_whenAccessViaTeam_returnsTrue() {
194     GsonRepositoryTeam team1 = mockGithubTeam("team1", 1, "role1", "read", "another_perm");
195     GsonRepositoryTeam team2 = mockGithubTeam("team2", 2, "role2", "another_perm", UserRole.SCAN);
196     mockTeamsFromApi(team1, team2);
197     bindGroupsToUser(team1.name(), team2.name());
198
199     assertThat(githubProjectCreator.isScanAllowedUsingPermissionsFromDevopsPlatform()).isTrue();
200   }
201
202   @Test
203   void isScanAllowedUsingPermissionsFromDevopsPlatform_whenAccessViaTeamButUserNotInTeam_returnsFalse() {
204     GsonRepositoryTeam team1 = mockGithubTeam("team1", 1, "role1", "read", "another_perm");
205     GsonRepositoryTeam team2 = mockGithubTeam("team2", 2, "role2", "another_perm", UserRole.SCAN);
206     mockTeamsFromApi(team1, team2);
207     bindGroupsToUser(team1.name());
208
209     assertThat(githubProjectCreator.isScanAllowedUsingPermissionsFromDevopsPlatform()).isFalse();
210   }
211
212   private void bindSessionToCollaborator(GsonRepositoryCollaborator collaborator1) {
213     UserSession.ExternalIdentity externalIdentity = new UserSession.ExternalIdentity(String.valueOf(collaborator1.id()), collaborator1.name());
214     when(userSession.getExternalIdentity()).thenReturn(Optional.of(externalIdentity));
215   }
216
217   private GsonRepositoryCollaborator mockCollaborator(String collaboratorLogin, int id, String role1, String... sqPermissions) {
218     GsonRepositoryCollaborator collaborator = new GsonRepositoryCollaborator(collaboratorLogin, id, role1,
219       new GsonRepositoryPermissions(false, false, false, false, false));
220     mockPermissionsConversion(collaborator, sqPermissions);
221     return collaborator;
222   }
223
224   private void mockGithubCollaboratorsFromApi(GsonRepositoryCollaborator... repositoryCollaborators) {
225     Set<GsonRepositoryCollaborator> collaborators = Arrays.stream(repositoryCollaborators).collect(toSet());
226     when(githubApplicationClient.getRepositoryCollaborators(DEVOPS_PROJECT_DESCRIPTOR.url(), authAppInstallationToken, ORGANIZATION_NAME, REPOSITORY_NAME)).thenReturn(
227       collaborators);
228   }
229
230   private GsonRepositoryTeam mockGithubTeam(String name, int id, String role, String... sqPermissions) {
231     GsonRepositoryTeam gsonRepositoryTeam = new GsonRepositoryTeam(name, id, name + "slug", role, new GsonRepositoryPermissions(false, false, false, false, false));
232     mockPermissionsConversion(gsonRepositoryTeam, sqPermissions);
233     return gsonRepositoryTeam;
234   }
235
236   private void mockTeamsFromApi(GsonRepositoryTeam... repositoryTeams) {
237     when(githubApplicationClient.getRepositoryTeams(DEVOPS_PROJECT_DESCRIPTOR.url(), authAppInstallationToken, ORGANIZATION_NAME, REPOSITORY_NAME))
238       .thenReturn(Arrays.stream(repositoryTeams).collect(toSet()));
239   }
240
241   private void mockPermissionsConversion(GsonRepositoryCollaborator collaborator, String... sqPermissions) {
242     Set<GithubPermissionsMappingDto> githubPermissionsMappingDtos = mockPermissionsMappingsDtos();
243     lenient().when(githubPermissionConverter.toSonarqubeRolesWithFallbackOnRepositoryPermissions(githubPermissionsMappingDtos, collaborator.roleName(), collaborator.permissions()))
244       .thenReturn(Arrays.stream(sqPermissions).collect(toSet()));
245   }
246
247   private void mockPermissionsConversion(GsonRepositoryTeam team, String... sqPermissions) {
248     Set<GithubPermissionsMappingDto> githubPermissionsMappingDtos = mockPermissionsMappingsDtos();
249     lenient().when(githubPermissionConverter.toSonarqubeRolesWithFallbackOnRepositoryPermissions(githubPermissionsMappingDtos, team.permission(), team.permissions()))
250       .thenReturn(Arrays.stream(sqPermissions).collect(toSet()));
251   }
252
253   private Set<GithubPermissionsMappingDto> mockPermissionsMappingsDtos() {
254     Set<GithubPermissionsMappingDto> githubPermissionsMappingDtos = Set.of(mock(GithubPermissionsMappingDto.class));
255     when(dbClient.githubPermissionsMappingDao().findAll(any())).thenReturn(githubPermissionsMappingDtos);
256     return githubPermissionsMappingDtos;
257   }
258
259   private void bindGroupsToUser(String... groupNames) {
260     Set<GroupDto> groupDtos = Arrays.stream(groupNames)
261       .map(groupName -> new GroupDto().setName(ORGANIZATION_NAME + "/" + groupName).setUuid("uuid_" + groupName))
262       .collect(toSet());
263     when(userSession.getGroups()).thenReturn(groupDtos);
264   }
265
266   @Test
267   void createProjectAndBindToDevOpsPlatform_whenRepoNotFound_throws() {
268     assertThatIllegalStateException().isThrownBy(
269       () -> githubProjectCreator.createProjectAndBindToDevOpsPlatform(mock(), SCANNER_API_DEVOPS_AUTO_CONFIG, false, null, null))
270       .withMessage("Impossible to find the repository 'orga2/repo1' on GitHub, using the devops config " + ALM_SETTING_KEY);
271   }
272
273   @Test
274   void createProjectAndBindToDevOpsPlatformFromScanner_whenRepoFoundOnGitHub_successfullyCreatesProject() {
275     // given
276     mockGitHubRepository();
277
278     ComponentCreationData componentCreationData = mockProjectCreation("generated_orga2/repo1");
279     ProjectAlmSettingDao projectAlmSettingDao = mock();
280     when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao);
281     when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE);
282
283     // when
284     ComponentCreationData actualComponentCreationData = githubProjectCreator.createProjectAndBindToDevOpsPlatform(dbClient.openSession(true),
285       SCANNER_API_DEVOPS_AUTO_CONFIG, false, null, null);
286
287     // then
288     assertThat(actualComponentCreationData).isEqualTo(componentCreationData);
289
290     ComponentCreationParameters componentCreationParameters = componentCreationParametersCaptor.getValue();
291     assertComponentCreationParametersContainsCorrectInformation(componentCreationParameters, "generated_orga2/repo1", SCANNER_API_DEVOPS_AUTO_CONFIG);
292     assertThat(componentCreationParameters.isManaged()).isFalse();
293     assertThat(componentCreationParameters.newComponent().isPrivate()).isTrue();
294
295     verify(projectAlmSettingDao).insertOrUpdate(any(), projectAlmSettingDtoCaptor.capture(), eq(ALM_SETTING_KEY), eq(REPOSITORY_NAME), eq("generated_orga2/repo1"));
296     ProjectAlmSettingDto projectAlmSettingDto = projectAlmSettingDtoCaptor.getValue();
297     assertAlmSettingsDtoContainsCorrectInformation(almSettingDto, requireNonNull(componentCreationData.projectDto()), projectAlmSettingDto);
298   }
299
300   @Test
301   void createProjectAndBindToDevOpsPlatformFromScanner_whenRepoFoundOnGitHubAndVisibilitySynchronizationEnabled_successfullyCreatesProjectAndSetsVisibility() {
302     // given
303     mockPublicGithubRepository();
304
305     ComponentCreationData componentCreationData = mockProjectCreation("generated_orga2/repo1");
306     ProjectAlmSettingDao projectAlmSettingDao = mock();
307     when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao);
308     when(gitHubSettings.isProvisioningEnabled()).thenReturn(true);
309     when(gitHubSettings.isProjectVisibilitySynchronizationActivated()).thenReturn(true);
310
311     // when
312     ComponentCreationData actualComponentCreationData = githubProjectCreator.createProjectAndBindToDevOpsPlatform(dbClient.openSession(true),
313       SCANNER_API_DEVOPS_AUTO_CONFIG, false, null, null);
314
315     // then
316     assertThat(actualComponentCreationData).isEqualTo(componentCreationData);
317
318     ComponentCreationParameters componentCreationParameters = componentCreationParametersCaptor.getValue();
319     assertThat(componentCreationParameters.newComponent().isPrivate()).isFalse();
320   }
321
322   @Test
323   void createProjectAndBindToDevOpsPlatformFromScanner_whenRepoFoundOnGitHubAndVisibilitySynchronizationDisabled_successfullyCreatesProjectAndMakesProjectPrivate() {
324     // given
325     mockGitHubRepository();
326
327     ComponentCreationData componentCreationData = mockProjectCreation("generated_orga2/repo1");
328     ProjectAlmSettingDao projectAlmSettingDao = mock();
329     when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao);
330     when(gitHubSettings.isProvisioningEnabled()).thenReturn(true);
331     when(gitHubSettings.isProjectVisibilitySynchronizationActivated()).thenReturn(false);
332
333     // when
334     ComponentCreationData actualComponentCreationData = githubProjectCreator.createProjectAndBindToDevOpsPlatform(dbClient.openSession(true),
335       SCANNER_API_DEVOPS_AUTO_CONFIG, false, null, null);
336
337     // then
338     assertThat(actualComponentCreationData).isEqualTo(componentCreationData);
339
340     ComponentCreationParameters componentCreationParameters = componentCreationParametersCaptor.getValue();
341     assertThat(componentCreationParameters.newComponent().isPrivate()).isTrue();
342   }
343
344   @Test
345   void createProjectAndBindToDevOpsPlatformFromApi_whenRepoFoundOnGitHub_successfullyCreatesProject() {
346     // given
347     String projectKey = "customProjectKey";
348     mockGitHubRepository();
349
350     ComponentCreationData componentCreationData = mockProjectCreation(projectKey);
351     ProjectAlmSettingDao projectAlmSettingDao = mock();
352     when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao);
353     when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE);
354
355     // when
356     ComponentCreationData actualComponentCreationData = githubProjectCreator.createProjectAndBindToDevOpsPlatform(dbClient.openSession(true), ALM_IMPORT_API, false, projectKey,
357       null);
358
359     // then
360     assertThat(actualComponentCreationData).isEqualTo(componentCreationData);
361
362     ComponentCreationParameters componentCreationParameters = componentCreationParametersCaptor.getValue();
363     assertComponentCreationParametersContainsCorrectInformation(componentCreationParameters, projectKey, ALM_IMPORT_API);
364     assertThat(componentCreationParameters.isManaged()).isFalse();
365     assertThat(componentCreationParameters.newComponent().isPrivate()).isTrue();
366
367     verify(projectAlmSettingDao).insertOrUpdate(any(), projectAlmSettingDtoCaptor.capture(), eq(ALM_SETTING_KEY), eq(REPOSITORY_NAME), eq(projectKey));
368     ProjectAlmSettingDto projectAlmSettingDto = projectAlmSettingDtoCaptor.getValue();
369     assertAlmSettingsDtoContainsCorrectInformation(almSettingDto, requireNonNull(componentCreationData.projectDto()), projectAlmSettingDto);
370   }
371
372   @Captor
373   private ArgumentCaptor<Collection<UserPermissionChange>> permissionChangesCaptor;
374
375   @Test
376   void createProjectAndBindToDevOpsPlatformFromApi_whenRepoFoundOnGitHubAutoProvisioningOnAndRepoPrivate_successfullyCreatesProject() {
377     // given
378     String projectKey = "customProjectKey";
379     mockGitHubRepository();
380
381     ComponentCreationData componentCreationData = mockProjectCreation(projectKey);
382     ProjectAlmSettingDao projectAlmSettingDao = mock();
383     when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao);
384     when(gitHubSettings.isProvisioningEnabled()).thenReturn(true);
385
386     // when
387     ComponentCreationData actualComponentCreationData = githubProjectCreator.createProjectAndBindToDevOpsPlatform(dbClient.openSession(true), ALM_IMPORT_API, false, projectKey,
388       null);
389
390     // then
391     assertThat(actualComponentCreationData).isEqualTo(componentCreationData);
392
393     ComponentCreationParameters componentCreationParameters = componentCreationParametersCaptor.getValue();
394     assertComponentCreationParametersContainsCorrectInformation(componentCreationParameters, projectKey, ALM_IMPORT_API);
395     assertThat(componentCreationParameters.isManaged()).isTrue();
396     assertThat(componentCreationParameters.newComponent().isPrivate()).isTrue();
397
398     verifyScanPermissionWasAddedToUser(actualComponentCreationData);
399     verifyProjectSyncTaskWasCreated(actualComponentCreationData);
400
401     verify(projectAlmSettingDao).insertOrUpdate(any(), projectAlmSettingDtoCaptor.capture(), eq(ALM_SETTING_KEY), eq(REPOSITORY_NAME), eq(projectKey));
402     ProjectAlmSettingDto projectAlmSettingDto = projectAlmSettingDtoCaptor.getValue();
403     assertAlmSettingsDtoContainsCorrectInformation(almSettingDto, requireNonNull(componentCreationData.projectDto()), projectAlmSettingDto);
404   }
405
406   private void verifyProjectSyncTaskWasCreated(ComponentCreationData componentCreationData) {
407     String projectUuid = requireNonNull(componentCreationData.projectDto()).getUuid();
408     String mainBranchUuid = requireNonNull(componentCreationData.mainBranchDto()).getUuid();
409     verify(managedProjectService).queuePermissionSyncTask(USER_UUID, mainBranchUuid, projectUuid);
410   }
411
412   private void verifyScanPermissionWasAddedToUser(ComponentCreationData actualComponentCreationData) {
413     verify(permissionUpdater).apply(any(), permissionChangesCaptor.capture());
414     UserPermissionChange permissionChange = permissionChangesCaptor.getValue().iterator().next();
415     assertThat(permissionChange.getUserId().getUuid()).isEqualTo(userSession.getUuid());
416     assertThat(permissionChange.getUserId().getLogin()).isEqualTo(userSession.getLogin());
417     assertThat(permissionChange.getPermission()).isEqualTo(UserRole.SCAN);
418     assertThat(permissionChange.getProjectUuid()).isEqualTo(actualComponentCreationData.projectDto().getUuid());
419   }
420
421   private void mockPublicGithubRepository() {
422     GithubApplicationClient.Repository repository = mockGitHubRepository();
423     when(repository.isPrivate()).thenReturn(false);
424   }
425
426   private GithubApplicationClient.Repository mockGitHubRepository() {
427     GithubApplicationClient.Repository repository = mock();
428     when(repository.getDefaultBranch()).thenReturn(MAIN_BRANCH_NAME);
429     when(repository.getName()).thenReturn(REPOSITORY_NAME);
430     when(repository.getFullName()).thenReturn(DEVOPS_PROJECT_DESCRIPTOR.projectIdentifier());
431     lenient().when(repository.isPrivate()).thenReturn(true);
432     when(githubApplicationClient.getRepository(DEVOPS_PROJECT_DESCRIPTOR.url(), devOpsAppInstallationToken, DEVOPS_PROJECT_DESCRIPTOR.projectIdentifier())).thenReturn(
433       Optional.of(repository));
434     when(projectKeyGenerator.generateUniqueProjectKey(repository.getFullName())).thenReturn("generated_" + DEVOPS_PROJECT_DESCRIPTOR.projectIdentifier());
435     return repository;
436   }
437
438   private ComponentCreationData mockProjectCreation(String projectKey) {
439     ComponentCreationData componentCreationData = mock();
440     ProjectDto projectDto = mockProjectDto(projectKey);
441     when(componentCreationData.projectDto()).thenReturn(projectDto);
442     BranchDto branchDto = mock();
443     when(componentCreationData.mainBranchDto()).thenReturn(branchDto);
444     when(componentUpdater.createWithoutCommit(any(), componentCreationParametersCaptor.capture())).thenReturn(componentCreationData);
445     return componentCreationData;
446   }
447
448   private static ProjectDto mockProjectDto(String projectKey) {
449     ProjectDto projectDto = mock();
450     when(projectDto.getName()).thenReturn(REPOSITORY_NAME);
451     when(projectDto.getKey()).thenReturn(projectKey);
452     when(projectDto.getUuid()).thenReturn("project-uuid-1");
453     return projectDto;
454   }
455
456   private static void assertComponentCreationParametersContainsCorrectInformation(ComponentCreationParameters componentCreationParameters, String expectedKey,
457     CreationMethod expectedCreationMethod) {
458     assertThat(componentCreationParameters.creationMethod()).isEqualTo(expectedCreationMethod);
459     assertThat(componentCreationParameters.mainBranchName()).isEqualTo(MAIN_BRANCH_NAME);
460     assertThat(componentCreationParameters.userLogin()).isEqualTo(USER_LOGIN);
461     assertThat(componentCreationParameters.userUuid()).isEqualTo(USER_UUID);
462
463     NewComponent newComponent = componentCreationParameters.newComponent();
464     assertThat(newComponent.isProject()).isTrue();
465     assertThat(newComponent.qualifier()).isEqualTo(Qualifiers.PROJECT);
466     assertThat(newComponent.key()).isEqualTo(expectedKey);
467     assertThat(newComponent.name()).isEqualTo(REPOSITORY_NAME);
468   }
469
470   private static void assertAlmSettingsDtoContainsCorrectInformation(AlmSettingDto almSettingDto, ProjectDto projectDto, ProjectAlmSettingDto projectAlmSettingDto) {
471     assertThat(projectAlmSettingDto.getAlmRepo()).isEqualTo(DEVOPS_PROJECT_DESCRIPTOR.projectIdentifier());
472     assertThat(projectAlmSettingDto.getAlmSlug()).isNull();
473     assertThat(projectAlmSettingDto.getAlmSettingUuid()).isEqualTo(almSettingDto.getUuid());
474     assertThat(projectAlmSettingDto.getProjectUuid()).isEqualTo(projectDto.getUuid());
475     assertThat(projectAlmSettingDto.getMonorepo()).isFalse();
476     assertThat(projectAlmSettingDto.getSummaryCommentEnabled()).isTrue();
477   }
478 }