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