3 * Copyright (C) 2009-2023 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.almsettings.ws;
22 import java.util.Optional;
24 import javax.annotation.CheckForNull;
25 import javax.annotation.Nullable;
26 import org.sonar.alm.client.github.AppInstallationToken;
27 import org.sonar.alm.client.github.GithubApplicationClient;
28 import org.sonar.alm.client.github.api.GsonRepositoryCollaborator;
29 import org.sonar.alm.client.github.api.GsonRepositoryTeam;
30 import org.sonar.alm.client.github.security.AccessToken;
31 import org.sonar.api.web.UserRole;
32 import org.sonar.alm.client.github.GithubPermissionConverter;
33 import org.sonar.auth.github.GsonRepositoryPermissions;
34 import org.sonar.db.DbClient;
35 import org.sonar.db.DbSession;
36 import org.sonar.db.alm.setting.AlmSettingDto;
37 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
38 import org.sonar.db.component.BranchDto;
39 import org.sonar.db.project.CreationMethod;
40 import org.sonar.db.project.ProjectDto;
41 import org.sonar.db.provisioning.GithubPermissionsMappingDto;
42 import org.sonar.db.user.GroupDto;
43 import org.sonar.db.user.UserIdDto;
44 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
45 import org.sonar.server.common.permission.Operation;
46 import org.sonar.server.component.ComponentCreationData;
47 import org.sonar.server.component.ComponentCreationParameters;
48 import org.sonar.server.component.ComponentUpdater;
49 import org.sonar.server.component.NewComponent;
50 import org.sonar.server.management.ManagedProjectService;
51 import org.sonar.server.permission.PermissionService;
52 import org.sonar.server.permission.PermissionUpdater;
53 import org.sonar.server.permission.UserPermissionChange;
54 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.resources.Qualifiers.PROJECT;
59 import static org.sonar.api.utils.Preconditions.checkState;
60 import static org.sonar.server.component.NewComponent.newComponentBuilder;
62 public class GithubProjectCreator implements DevOpsProjectCreator {
64 private final DbClient dbClient;
65 private final GithubApplicationClient githubApplicationClient;
66 private final GithubPermissionConverter githubPermissionConverter;
67 private final ProjectKeyGenerator projectKeyGenerator;
68 private final ComponentUpdater componentUpdater;
69 private final PermissionUpdater<UserPermissionChange> permissionUpdater;
70 private final PermissionService permissionService;
71 private final ManagedProjectService managedProjectService;
72 private final GithubProjectCreationParameters githubProjectCreationParameters;
73 private final DevOpsProjectDescriptor devOpsProjectDescriptor;
74 private final UserSession userSession;
75 private final AlmSettingDto almSettingDto;
76 private final AccessToken devOpsAppInstallationToken;
79 private final AppInstallationToken authAppInstallationToken;
81 public GithubProjectCreator(DbClient dbClient, GithubApplicationClient githubApplicationClient, GithubPermissionConverter githubPermissionConverter,
82 ProjectKeyGenerator projectKeyGenerator, ComponentUpdater componentUpdater, PermissionUpdater<UserPermissionChange> permissionUpdater, PermissionService permissionService,
83 ManagedProjectService managedProjectService, GithubProjectCreationParameters githubProjectCreationParameters) {
85 this.dbClient = dbClient;
86 this.githubApplicationClient = githubApplicationClient;
87 this.githubPermissionConverter = githubPermissionConverter;
88 this.projectKeyGenerator = projectKeyGenerator;
89 this.componentUpdater = componentUpdater;
90 this.permissionUpdater = permissionUpdater;
91 this.permissionService = permissionService;
92 this.managedProjectService = managedProjectService;
93 this.githubProjectCreationParameters = githubProjectCreationParameters;
94 userSession = githubProjectCreationParameters.userSession();
95 almSettingDto = githubProjectCreationParameters.almSettingDto();
96 devOpsProjectDescriptor = githubProjectCreationParameters.devOpsProjectDescriptor();
97 devOpsAppInstallationToken = githubProjectCreationParameters.devOpsAppInstallationToken();
98 authAppInstallationToken = githubProjectCreationParameters.authAppInstallationToken();
102 public boolean isScanAllowedUsingPermissionsFromDevopsPlatform() {
103 checkState(githubProjectCreationParameters.authAppInstallationToken() != null, "An auth app token is required in case repository permissions checking is necessary.");
105 String[] orgaAndRepoTokenified = devOpsProjectDescriptor.projectIdentifier().split("/");
106 String organization = orgaAndRepoTokenified[0];
107 String repository = orgaAndRepoTokenified[1];
109 Set<GithubPermissionsMappingDto> permissionsMappingDtos = dbClient.githubPermissionsMappingDao().findAll(dbClient.openSession(false));
111 boolean userHasDirectAccessToRepo = doesUserHaveScanPermission(organization, repository, permissionsMappingDtos);
112 if (userHasDirectAccessToRepo) {
115 return doesUserBelongToAGroupWithScanPermission(organization, repository, permissionsMappingDtos);
118 private boolean doesUserHaveScanPermission(String organization, String repository, Set<GithubPermissionsMappingDto> permissionsMappingDtos) {
119 Set<GsonRepositoryCollaborator> repositoryCollaborators = githubApplicationClient.getRepositoryCollaborators(devOpsProjectDescriptor.url(), authAppInstallationToken,
120 organization, repository);
122 String externalLogin = userSession.getExternalIdentity().map(UserSession.ExternalIdentity::login).orElse(null);
123 if (externalLogin == null) {
126 return repositoryCollaborators.stream()
127 .filter(gsonRepositoryCollaborator -> externalLogin.equals(gsonRepositoryCollaborator.name()))
129 .map(gsonRepositoryCollaborator -> hasScanPermission(permissionsMappingDtos, gsonRepositoryCollaborator.roleName(), gsonRepositoryCollaborator.permissions()))
133 private boolean doesUserBelongToAGroupWithScanPermission(String organization, String repository,
134 Set<GithubPermissionsMappingDto> permissionsMappingDtos) {
135 Set<GsonRepositoryTeam> repositoryTeams = githubApplicationClient.getRepositoryTeams(devOpsProjectDescriptor.url(), authAppInstallationToken, organization, repository);
137 Set<String> groupsOfUser = findUserMembershipOnSonarQube(organization);
138 return repositoryTeams.stream()
139 .filter(team -> hasScanPermission(permissionsMappingDtos, team.permission(), team.permissions()))
140 .map(GsonRepositoryTeam::name)
141 .anyMatch(groupsOfUser::contains);
144 private Set<String> findUserMembershipOnSonarQube(String organization) {
145 return userSession.getGroups().stream()
146 .map(GroupDto::getName)
147 .filter(groupName -> groupName.contains("/"))
148 .map(name -> name.replaceFirst(organization + "/", ""))
152 private boolean hasScanPermission(Set<GithubPermissionsMappingDto> permissionsMappingDtos, String role, GsonRepositoryPermissions permissions) {
153 Set<String> sonarqubePermissions = githubPermissionConverter.toSonarqubeRolesWithFallbackOnRepositoryPermissions(permissionsMappingDtos,
155 return sonarqubePermissions.contains(UserRole.SCAN);
159 public ComponentCreationData createProjectAndBindToDevOpsPlatform(DbSession dbSession, CreationMethod creationMethod, @Nullable String projectKey) {
160 String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
161 GithubApplicationClient.Repository repository = githubApplicationClient.getRepository(url, devOpsAppInstallationToken, devOpsProjectDescriptor.projectIdentifier())
162 .orElseThrow(() -> new IllegalStateException(
163 String.format("Impossible to find the repository '%s' on GitHub, using the devops config %s", devOpsProjectDescriptor.projectIdentifier(), almSettingDto.getKey())));
165 return createProjectAndBindToDevOpsPlatform(dbSession, projectKey, almSettingDto, repository, creationMethod);
168 private ComponentCreationData createProjectAndBindToDevOpsPlatform(DbSession dbSession, @Nullable String projectKey, AlmSettingDto almSettingDto,
169 GithubApplicationClient.Repository repository, CreationMethod creationMethod) {
170 ComponentCreationData componentCreationData = createProject(dbSession, projectKey, repository, creationMethod);
171 ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
172 createProjectAlmSettingDto(dbSession, repository, projectDto, almSettingDto);
173 addScanPermissionToCurrentUser(dbSession, projectDto);
175 BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
176 syncProjectPermissionsWithGithub(projectDto, mainBranchDto);
177 return componentCreationData;
180 private void addScanPermissionToCurrentUser(DbSession dbSession, ProjectDto projectDto) {
181 UserIdDto userId = new UserIdDto(requireNonNull(userSession.getUuid()), requireNonNull(userSession.getLogin()));
182 UserPermissionChange scanPermission = new UserPermissionChange(Operation.ADD, UserRole.SCAN, projectDto, userId, permissionService);
183 permissionUpdater.apply(dbSession, Set.of(scanPermission));
186 private void syncProjectPermissionsWithGithub(ProjectDto projectDto, BranchDto mainBranchDto) {
187 String userUuid = requireNonNull(userSession.getUuid());
188 managedProjectService.queuePermissionSyncTask(userUuid, mainBranchDto.getUuid(), projectDto.getUuid());
191 private ComponentCreationData createProject(DbSession dbSession, @Nullable String projectKey, GithubApplicationClient.Repository repository, CreationMethod creationMethod) {
192 NewComponent projectComponent = newComponentBuilder()
193 .setKey(Optional.ofNullable(projectKey).orElse(getUniqueProjectKey(repository)))
194 .setName(repository.getName())
195 .setPrivate(githubProjectCreationParameters.projectsArePrivateByDefault())
196 .setQualifier(PROJECT)
198 ComponentCreationParameters componentCreationParameters = ComponentCreationParameters.builder()
199 .newComponent(projectComponent)
200 .userLogin(userSession.getLogin())
201 .userUuid(userSession.getUuid())
202 .mainBranchName(repository.getDefaultBranch())
203 .isManaged(githubProjectCreationParameters.isProvisioningEnabled())
204 .creationMethod(creationMethod)
206 return componentUpdater.createWithoutCommit(dbSession, componentCreationParameters);
209 private String getUniqueProjectKey(GithubApplicationClient.Repository repository) {
210 return projectKeyGenerator.generateUniqueProjectKey(repository.getFullName());
213 private void createProjectAlmSettingDto(DbSession dbSession, GithubApplicationClient.Repository repo, ProjectDto projectDto, AlmSettingDto almSettingDto) {
214 ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
215 .setAlmSettingUuid(almSettingDto.getUuid())
216 .setAlmRepo(repo.getFullName())
218 .setProjectUuid(projectDto.getUuid())
219 .setSummaryCommentEnabled(true)
221 dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(), projectDto.getName(), projectDto.getKey());