You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GithubProjectCreator.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. import java.util.Optional;
  22. import java.util.Set;
  23. import javax.annotation.CheckForNull;
  24. import javax.annotation.Nullable;
  25. import org.sonar.alm.client.github.GithubPermissionConverter;
  26. import org.sonar.api.web.UserRole;
  27. import org.sonar.auth.github.AppInstallationToken;
  28. import org.sonar.auth.github.GitHubSettings;
  29. import org.sonar.auth.github.GsonRepositoryCollaborator;
  30. import org.sonar.auth.github.GsonRepositoryPermissions;
  31. import org.sonar.auth.github.GsonRepositoryTeam;
  32. import org.sonar.auth.github.client.GithubApplicationClient;
  33. import org.sonar.auth.github.client.GithubApplicationClient.Repository;
  34. import org.sonar.auth.github.security.AccessToken;
  35. import org.sonar.db.DbClient;
  36. import org.sonar.db.DbSession;
  37. import org.sonar.db.alm.setting.AlmSettingDto;
  38. import org.sonar.db.alm.setting.ProjectAlmSettingDto;
  39. import org.sonar.db.component.BranchDto;
  40. import org.sonar.db.project.CreationMethod;
  41. import org.sonar.db.project.ProjectDto;
  42. import org.sonar.db.provisioning.GithubPermissionsMappingDto;
  43. import org.sonar.db.user.GroupDto;
  44. import org.sonar.db.user.UserIdDto;
  45. import org.sonar.server.common.almintegration.ProjectKeyGenerator;
  46. import org.sonar.server.common.almsettings.DevOpsProjectCreator;
  47. import org.sonar.server.common.almsettings.DevOpsProjectDescriptor;
  48. import org.sonar.server.common.permission.Operation;
  49. import org.sonar.server.common.permission.PermissionUpdater;
  50. import org.sonar.server.common.permission.UserPermissionChange;
  51. import org.sonar.server.common.project.ProjectCreator;
  52. import org.sonar.server.component.ComponentCreationData;
  53. import org.sonar.server.management.ManagedProjectService;
  54. import org.sonar.server.permission.PermissionService;
  55. import org.sonar.server.user.UserSession;
  56. import static java.util.Objects.requireNonNull;
  57. import static java.util.stream.Collectors.toSet;
  58. import static org.sonar.api.utils.Preconditions.checkState;
  59. public class GithubProjectCreator implements DevOpsProjectCreator {
  60. private final DbClient dbClient;
  61. private final GithubApplicationClient githubApplicationClient;
  62. private final GithubPermissionConverter githubPermissionConverter;
  63. private final ProjectKeyGenerator projectKeyGenerator;
  64. private final PermissionUpdater<UserPermissionChange> permissionUpdater;
  65. private final PermissionService permissionService;
  66. private final ManagedProjectService managedProjectService;
  67. private final ProjectCreator projectCreator;
  68. private final GithubProjectCreationParameters githubProjectCreationParameters;
  69. private final DevOpsProjectDescriptor devOpsProjectDescriptor;
  70. private final UserSession userSession;
  71. private final AlmSettingDto almSettingDto;
  72. private final AccessToken devOpsAppInstallationToken;
  73. private final GitHubSettings gitHubSettings;
  74. @CheckForNull
  75. private final AppInstallationToken authAppInstallationToken;
  76. public GithubProjectCreator(DbClient dbClient, GithubApplicationClient githubApplicationClient, GithubPermissionConverter githubPermissionConverter,
  77. ProjectKeyGenerator projectKeyGenerator, PermissionUpdater<UserPermissionChange> permissionUpdater, PermissionService permissionService,
  78. ManagedProjectService managedProjectService, ProjectCreator projectCreator, GithubProjectCreationParameters githubProjectCreationParameters, GitHubSettings gitHubSettings) {
  79. this.dbClient = dbClient;
  80. this.githubApplicationClient = githubApplicationClient;
  81. this.githubPermissionConverter = githubPermissionConverter;
  82. this.projectKeyGenerator = projectKeyGenerator;
  83. this.permissionUpdater = permissionUpdater;
  84. this.permissionService = permissionService;
  85. this.managedProjectService = managedProjectService;
  86. this.projectCreator = projectCreator;
  87. this.githubProjectCreationParameters = githubProjectCreationParameters;
  88. userSession = githubProjectCreationParameters.userSession();
  89. almSettingDto = githubProjectCreationParameters.almSettingDto();
  90. devOpsProjectDescriptor = githubProjectCreationParameters.devOpsProjectDescriptor();
  91. devOpsAppInstallationToken = githubProjectCreationParameters.devOpsAppInstallationToken();
  92. authAppInstallationToken = githubProjectCreationParameters.authAppInstallationToken();
  93. this.gitHubSettings = gitHubSettings;
  94. }
  95. @Override
  96. public boolean isScanAllowedUsingPermissionsFromDevopsPlatform() {
  97. checkState(githubProjectCreationParameters.authAppInstallationToken() != null, "An auth app token is required in case repository permissions checking is necessary.");
  98. String[] orgaAndRepoTokenified = devOpsProjectDescriptor.projectIdentifier().split("/");
  99. String organization = orgaAndRepoTokenified[0];
  100. String repository = orgaAndRepoTokenified[1];
  101. Set<GithubPermissionsMappingDto> permissionsMappingDtos = dbClient.githubPermissionsMappingDao().findAll(dbClient.openSession(false));
  102. boolean userHasDirectAccessToRepo = doesUserHaveScanPermission(organization, repository, permissionsMappingDtos);
  103. if (userHasDirectAccessToRepo) {
  104. return true;
  105. }
  106. return doesUserBelongToAGroupWithScanPermission(organization, repository, permissionsMappingDtos);
  107. }
  108. private boolean doesUserHaveScanPermission(String organization, String repository, Set<GithubPermissionsMappingDto> permissionsMappingDtos) {
  109. Set<GsonRepositoryCollaborator> repositoryCollaborators = githubApplicationClient.getRepositoryCollaborators(devOpsProjectDescriptor.url(), authAppInstallationToken,
  110. organization, repository);
  111. String externalLogin = userSession.getExternalIdentity().map(UserSession.ExternalIdentity::login).orElse(null);
  112. if (externalLogin == null) {
  113. return false;
  114. }
  115. return repositoryCollaborators.stream()
  116. .filter(gsonRepositoryCollaborator -> externalLogin.equals(gsonRepositoryCollaborator.name()))
  117. .findAny()
  118. .map(gsonRepositoryCollaborator -> hasScanPermission(permissionsMappingDtos, gsonRepositoryCollaborator.roleName(), gsonRepositoryCollaborator.permissions()))
  119. .orElse(false);
  120. }
  121. private boolean doesUserBelongToAGroupWithScanPermission(String organization, String repository,
  122. Set<GithubPermissionsMappingDto> permissionsMappingDtos) {
  123. Set<GsonRepositoryTeam> repositoryTeams = githubApplicationClient.getRepositoryTeams(devOpsProjectDescriptor.url(), authAppInstallationToken, organization, repository);
  124. Set<String> groupsOfUser = findUserMembershipOnSonarQube(organization);
  125. return repositoryTeams.stream()
  126. .filter(team -> hasScanPermission(permissionsMappingDtos, team.permission(), team.permissions()))
  127. .map(GsonRepositoryTeam::name)
  128. .anyMatch(groupsOfUser::contains);
  129. }
  130. private Set<String> findUserMembershipOnSonarQube(String organization) {
  131. return userSession.getGroups().stream()
  132. .map(GroupDto::getName)
  133. .filter(groupName -> groupName.contains("/"))
  134. .map(name -> name.replaceFirst(organization + "/", ""))
  135. .collect(toSet());
  136. }
  137. private boolean hasScanPermission(Set<GithubPermissionsMappingDto> permissionsMappingDtos, String role, GsonRepositoryPermissions permissions) {
  138. Set<String> sonarqubePermissions = githubPermissionConverter.toSonarqubeRolesWithFallbackOnRepositoryPermissions(permissionsMappingDtos,
  139. role, permissions);
  140. return sonarqubePermissions.contains(UserRole.SCAN);
  141. }
  142. @Override
  143. public ComponentCreationData createProjectAndBindToDevOpsPlatform(DbSession dbSession, CreationMethod creationMethod, Boolean monorepo, @Nullable String projectKey,
  144. @Nullable String projectName) {
  145. String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
  146. Repository repository = githubApplicationClient.getRepository(url, devOpsAppInstallationToken, devOpsProjectDescriptor.projectIdentifier())
  147. .orElseThrow(() -> new IllegalStateException(
  148. String.format("Impossible to find the repository '%s' on GitHub, using the devops config %s", devOpsProjectDescriptor.projectIdentifier(), almSettingDto.getKey())));
  149. return createProjectAndBindToDevOpsPlatform(dbSession, monorepo, projectKey, projectName, almSettingDto, repository, creationMethod);
  150. }
  151. private ComponentCreationData createProjectAndBindToDevOpsPlatform(DbSession dbSession, Boolean monorepo, @Nullable String projectKey, @Nullable String projectName,
  152. AlmSettingDto almSettingDto,
  153. Repository repository, CreationMethod creationMethod) {
  154. String key = Optional.ofNullable(projectKey).orElse(getUniqueProjectKey(repository));
  155. boolean isManaged = gitHubSettings.isProvisioningEnabled();
  156. ComponentCreationData componentCreationData = projectCreator.createProject(dbSession, key, Optional.ofNullable(projectName).orElse(repository.getName()),
  157. repository.getDefaultBranch(), creationMethod,
  158. shouldProjectBePrivate(repository), isManaged);
  159. ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
  160. createProjectAlmSettingDto(dbSession, repository, projectDto, almSettingDto, monorepo);
  161. addScanPermissionToCurrentUser(dbSession, projectDto);
  162. BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
  163. if (gitHubSettings.isProvisioningEnabled()) {
  164. syncProjectPermissionsWithGithub(projectDto, mainBranchDto);
  165. }
  166. return componentCreationData;
  167. }
  168. @CheckForNull
  169. private Boolean shouldProjectBePrivate(Repository repository) {
  170. if (gitHubSettings.isProvisioningEnabled() && gitHubSettings.isProjectVisibilitySynchronizationActivated()) {
  171. return repository.isPrivate();
  172. } else if (gitHubSettings.isProvisioningEnabled()) {
  173. return true;
  174. } else {
  175. return null;
  176. }
  177. }
  178. private void addScanPermissionToCurrentUser(DbSession dbSession, ProjectDto projectDto) {
  179. UserIdDto userId = new UserIdDto(requireNonNull(userSession.getUuid()), requireNonNull(userSession.getLogin()));
  180. UserPermissionChange scanPermission = new UserPermissionChange(Operation.ADD, UserRole.SCAN, projectDto, userId, permissionService);
  181. permissionUpdater.apply(dbSession, Set.of(scanPermission));
  182. }
  183. private void syncProjectPermissionsWithGithub(ProjectDto projectDto, BranchDto mainBranchDto) {
  184. String userUuid = requireNonNull(userSession.getUuid());
  185. managedProjectService.queuePermissionSyncTask(userUuid, mainBranchDto.getUuid(), projectDto.getUuid());
  186. }
  187. private String getUniqueProjectKey(Repository repository) {
  188. return projectKeyGenerator.generateUniqueProjectKey(repository.getFullName());
  189. }
  190. private void createProjectAlmSettingDto(DbSession dbSession, Repository repo, ProjectDto projectDto, AlmSettingDto almSettingDto, Boolean monorepo) {
  191. ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
  192. .setAlmSettingUuid(almSettingDto.getUuid())
  193. .setAlmRepo(repo.getFullName())
  194. .setAlmSlug(null)
  195. .setProjectUuid(projectDto.getUuid())
  196. .setSummaryCommentEnabled(true)
  197. .setMonorepo(monorepo);
  198. dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(), projectDto.getName(), projectDto.getKey());
  199. }
  200. }