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

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