3 * Copyright (C) 2009-2021 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.permission;
22 import java.text.MessageFormat;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Iterator;
26 import java.util.List;
29 import java.util.stream.Collectors;
30 import javax.annotation.CheckForNull;
31 import javax.annotation.Nullable;
32 import org.apache.commons.lang.StringUtils;
33 import org.sonar.api.resources.Qualifiers;
34 import org.sonar.api.server.ServerSide;
35 import org.sonar.core.util.UuidFactory;
36 import org.sonar.db.DbClient;
37 import org.sonar.db.DbSession;
38 import org.sonar.db.component.ComponentDto;
39 import org.sonar.db.permission.GroupPermissionDto;
40 import org.sonar.db.permission.UserPermissionDto;
41 import org.sonar.db.permission.template.PermissionTemplateCharacteristicDto;
42 import org.sonar.db.permission.template.PermissionTemplateDto;
43 import org.sonar.db.permission.template.PermissionTemplateGroupDto;
44 import org.sonar.db.permission.template.PermissionTemplateUserDto;
45 import org.sonar.db.user.UserDto;
46 import org.sonar.db.user.UserId;
47 import org.sonar.server.es.ProjectIndexer;
48 import org.sonar.server.es.ProjectIndexers;
49 import org.sonar.server.permission.DefaultTemplatesResolver.ResolvedDefaultTemplates;
50 import org.sonar.server.user.UserSession;
52 import static com.google.common.base.Preconditions.checkArgument;
53 import static java.lang.String.format;
54 import static java.util.Collections.singletonList;
55 import static org.sonar.api.security.DefaultGroups.isAnyone;
56 import static org.sonar.api.web.UserRole.PUBLIC_PERMISSIONS;
57 import static org.sonar.db.permission.GlobalPermission.SCAN;
60 public class PermissionTemplateService {
62 private final DbClient dbClient;
63 private final ProjectIndexers projectIndexers;
64 private final UserSession userSession;
65 private final DefaultTemplatesResolver defaultTemplatesResolver;
66 private final UuidFactory uuidFactory;
68 public PermissionTemplateService(DbClient dbClient, ProjectIndexers projectIndexers, UserSession userSession,
69 DefaultTemplatesResolver defaultTemplatesResolver, UuidFactory uuidFactory) {
70 this.dbClient = dbClient;
71 this.projectIndexers = projectIndexers;
72 this.userSession = userSession;
73 this.defaultTemplatesResolver = defaultTemplatesResolver;
74 this.uuidFactory = uuidFactory;
77 public boolean wouldUserHaveScanPermissionWithDefaultTemplate(DbSession dbSession, @Nullable String userUuid, String projectKey) {
78 if (userSession.hasPermission(SCAN)) {
82 ComponentDto dto = new ComponentDto().setDbKey(projectKey).setQualifier(Qualifiers.PROJECT);
83 PermissionTemplateDto template = findTemplate(dbSession, dto);
84 if (template == null) {
88 List<String> potentialPermissions = dbClient.permissionTemplateDao().selectPotentialPermissionsByUserUuidAndTemplateUuid(dbSession, userUuid, template.getUuid());
89 return potentialPermissions.contains(SCAN.getKey());
93 * Apply a permission template to a set of projects. Authorization to administrate these projects
94 * is not verified. The projects must exist, so the "project creator" permissions defined in the
95 * template are ignored.
97 public void applyAndCommit(DbSession dbSession, PermissionTemplateDto template, Collection<ComponentDto> projects) {
98 if (projects.isEmpty()) {
102 for (ComponentDto project : projects) {
103 dbClient.groupPermissionDao().deleteByRootComponentUuid(dbSession, project);
104 dbClient.userPermissionDao().deleteProjectPermissions(dbSession, project);
105 copyPermissions(dbSession, template, project, null);
107 projectIndexers.commitAndIndexComponents(dbSession, projects, ProjectIndexer.Cause.PERMISSION_CHANGE);
111 * Apply the default permission template to a new project (has no permissions yet).
112 * @param projectCreatorUserId id of the user creating the project.
114 public void applyDefaultToNewComponent(DbSession dbSession, ComponentDto component, @Nullable String projectCreatorUserId) {
115 PermissionTemplateDto template = findTemplate(dbSession, component);
116 checkArgument(template != null, "Cannot retrieve default permission template");
117 copyPermissions(dbSession, template, component, projectCreatorUserId);
120 public boolean hasDefaultTemplateWithPermissionOnProjectCreator(DbSession dbSession, ComponentDto component) {
121 PermissionTemplateDto template = findTemplate(dbSession, component);
122 return hasProjectCreatorPermission(dbSession, template);
125 private boolean hasProjectCreatorPermission(DbSession dbSession, @Nullable PermissionTemplateDto template) {
126 return template != null && dbClient.permissionTemplateCharacteristicDao().selectByTemplateUuids(dbSession, singletonList(template.getUuid())).stream()
127 .anyMatch(PermissionTemplateCharacteristicDto::getWithProjectCreator);
130 private void copyPermissions(DbSession dbSession, PermissionTemplateDto template, ComponentDto project, @Nullable String projectCreatorUserUuid) {
131 List<PermissionTemplateUserDto> usersPermissions = dbClient.permissionTemplateDao().selectUserPermissionsByTemplateId(dbSession, template.getUuid());
132 Set<String> permissionTemplateUserUuids = usersPermissions.stream().map(PermissionTemplateUserDto::getUserUuid).collect(Collectors.toSet());
133 Map<String, UserId> userIdByUuid = dbClient.userDao().selectByUuids(dbSession, permissionTemplateUserUuids).stream().collect(Collectors.toMap(UserDto::getUuid, u -> u));
136 .filter(up -> permissionValidForProject(project, up.getPermission()))
138 UserPermissionDto dto = new UserPermissionDto(uuidFactory.create(), up.getPermission(), up.getUserUuid(), project.uuid());
139 dbClient.userPermissionDao().insert(dbSession, dto, project, userIdByUuid.get(up.getUserUuid()), template);
142 List<PermissionTemplateGroupDto> groupsPermissions = dbClient.permissionTemplateDao().selectGroupPermissionsByTemplateUuid(dbSession, template.getUuid());
145 .filter(gp -> groupNameValidForProject(project, gp.getGroupName()))
146 .filter(gp -> permissionValidForProject(project, gp.getPermission()))
148 String groupUuid = isAnyone(gp.getGroupName()) ? null : gp.getGroupUuid();
149 String groupName = groupUuid == null ? null : dbClient.groupDao().selectByUuid(dbSession, groupUuid).getName();
150 GroupPermissionDto dto = new GroupPermissionDto()
151 .setUuid(uuidFactory.create())
152 .setGroupUuid(groupUuid)
153 .setGroupName(groupName)
154 .setRole(gp.getPermission())
155 .setComponentUuid(project.uuid())
156 .setComponentName(project.name());
157 dbClient.groupPermissionDao().insert(dbSession, dto, project, template);
160 List<PermissionTemplateCharacteristicDto> characteristics = dbClient.permissionTemplateCharacteristicDao().selectByTemplateUuids(dbSession, singletonList(template.getUuid()));
161 if (projectCreatorUserUuid != null) {
162 Set<String> permissionsForCurrentUserAlreadyInDb = usersPermissions.stream()
163 .filter(userPermission -> projectCreatorUserUuid.equals(userPermission.getUserUuid()))
164 .map(PermissionTemplateUserDto::getPermission)
165 .collect(java.util.stream.Collectors.toSet());
167 UserDto userDto = dbClient.userDao().selectByUuid(dbSession, projectCreatorUserUuid);
168 characteristics.stream()
169 .filter(PermissionTemplateCharacteristicDto::getWithProjectCreator)
170 .filter(up -> permissionValidForProject(project, up.getPermission()))
171 .filter(characteristic -> !permissionsForCurrentUserAlreadyInDb.contains(characteristic.getPermission()))
173 UserPermissionDto dto = new UserPermissionDto(uuidFactory.create(), c.getPermission(), userDto.getUuid(), project.uuid());
174 dbClient.userPermissionDao().insert(dbSession, dto, project, userDto, template);
179 private static boolean permissionValidForProject(ComponentDto project, String permission) {
180 return project.isPrivate() || !PUBLIC_PERMISSIONS.contains(permission);
183 private static boolean groupNameValidForProject(ComponentDto project, String groupName) {
184 return !project.isPrivate() || !isAnyone(groupName);
188 * Return the permission template for the given component. If no template key pattern match then consider default
189 * template for the component qualifier.
192 private PermissionTemplateDto findTemplate(DbSession dbSession, ComponentDto component) {
193 List<PermissionTemplateDto> allPermissionTemplates = dbClient.permissionTemplateDao().selectAll(dbSession, null);
194 List<PermissionTemplateDto> matchingTemplates = new ArrayList<>();
195 for (PermissionTemplateDto permissionTemplateDto : allPermissionTemplates) {
196 String keyPattern = permissionTemplateDto.getKeyPattern();
197 if (StringUtils.isNotBlank(keyPattern) && component.getDbKey().matches(keyPattern)) {
198 matchingTemplates.add(permissionTemplateDto);
201 checkAtMostOneMatchForComponentKey(component.getDbKey(), matchingTemplates);
202 if (matchingTemplates.size() == 1) {
203 return matchingTemplates.get(0);
206 String qualifier = component.qualifier();
207 ResolvedDefaultTemplates resolvedDefaultTemplates = defaultTemplatesResolver.resolve(dbSession);
209 case Qualifiers.PROJECT:
210 return dbClient.permissionTemplateDao().selectByUuid(dbSession, resolvedDefaultTemplates.getProject());
211 case Qualifiers.VIEW:
212 String portDefaultTemplateUuid = resolvedDefaultTemplates.getPortfolio().orElseThrow(
213 () -> new IllegalStateException("Failed to find default template for portfolios"));
214 return dbClient.permissionTemplateDao().selectByUuid(dbSession, portDefaultTemplateUuid);
216 String appDefaultTemplateUuid = resolvedDefaultTemplates.getApplication().orElseThrow(
217 () -> new IllegalStateException("Failed to find default template for applications"));
218 return dbClient.permissionTemplateDao().selectByUuid(dbSession, appDefaultTemplateUuid);
220 throw new IllegalArgumentException(format("Qualifier '%s' is not supported", qualifier));
224 private static void checkAtMostOneMatchForComponentKey(String componentKey, List<PermissionTemplateDto> matchingTemplates) {
225 if (matchingTemplates.size() > 1) {
226 StringBuilder templatesNames = new StringBuilder();
227 for (Iterator<PermissionTemplateDto> it = matchingTemplates.iterator(); it.hasNext(); ) {
228 templatesNames.append("\"").append(it.next().getName()).append("\"");
230 templatesNames.append(", ");
233 throw new IllegalStateException(MessageFormat.format(
234 "The \"{0}\" key matches multiple permission templates: {1}."
235 + " A system administrator must update these templates so that only one of them matches the key.",
237 templatesNames.toString()));