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.permission.ws.template;
22 import com.google.common.collect.Multimap;
23 import com.google.common.collect.Ordering;
24 import com.google.common.collect.TreeMultimap;
25 import java.util.List;
26 import java.util.stream.Collectors;
27 import org.sonar.api.security.DefaultGroups;
28 import org.sonar.api.server.ws.Request;
29 import org.sonar.api.server.ws.Response;
30 import org.sonar.api.server.ws.WebService;
31 import org.sonar.api.utils.Paging;
32 import org.sonar.db.DbClient;
33 import org.sonar.db.DbSession;
34 import org.sonar.db.permission.PermissionQuery;
35 import org.sonar.db.permission.template.PermissionTemplateDto;
36 import org.sonar.db.permission.template.PermissionTemplateGroupDto;
37 import org.sonar.db.user.GroupDto;
38 import org.sonar.server.permission.RequestValidator;
39 import org.sonar.server.permission.ws.PermissionWsSupport;
40 import org.sonar.server.permission.ws.PermissionsWsAction;
41 import org.sonar.server.permission.ws.WsParameters;
42 import org.sonar.server.user.UserSession;
43 import org.sonarqube.ws.Permissions;
45 import static java.util.Optional.ofNullable;
46 import static org.sonar.api.server.ws.WebService.Param.PAGE;
47 import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
48 import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
49 import static org.sonar.db.permission.PermissionQuery.DEFAULT_PAGE_SIZE;
50 import static org.sonar.db.permission.PermissionQuery.RESULTS_MAX_SIZE;
51 import static org.sonar.db.permission.PermissionQuery.SEARCH_QUERY_MIN_LENGTH;
52 import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
53 import static org.sonar.server.permission.ws.WsParameters.createTemplateParameters;
54 import static org.sonar.server.ws.WsUtils.writeProtobuf;
55 import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
57 public class TemplateGroupsAction implements PermissionsWsAction {
58 private final DbClient dbClient;
59 private final UserSession userSession;
60 private final PermissionWsSupport wsSupport;
61 private final WsParameters wsParameters;
62 private final RequestValidator requestValidator;
64 public TemplateGroupsAction(DbClient dbClient, UserSession userSession, PermissionWsSupport wsSupport, WsParameters wsParameters, RequestValidator requestValidator) {
65 this.dbClient = dbClient;
66 this.userSession = userSession;
67 this.wsSupport = wsSupport;
68 this.wsParameters = wsParameters;
69 this.requestValidator = requestValidator;
73 public void define(WebService.NewController context) {
74 WebService.NewAction action = context.createAction("template_groups")
77 .setDescription("Lists the groups with their permission as individual groups rather than through user affiliation on the chosen template.<br />" +
78 "This service defaults to all groups, but can be limited to groups with a specific permission by providing the desired permission.<br>" +
79 "Requires the following permission: 'Administer System'.")
80 .addPagingParams(DEFAULT_PAGE_SIZE, RESULTS_MAX_SIZE)
81 .setResponseExample(getClass().getResource("template_groups-example.json"))
84 action.createParam(TEXT_QUERY)
85 .setMinimumLength(SEARCH_QUERY_MIN_LENGTH)
86 .setDescription("Limit search to group names that contain the supplied string. <br/>" +
87 "When this parameter is not set, only group having at least one permission are returned.")
88 .setExampleValue("eri");
90 wsParameters.createProjectPermissionParameter(action, false);
91 createTemplateParameters(action);
95 public void handle(Request wsRequest, Response wsResponse) throws Exception {
96 try (DbSession dbSession = dbClient.openSession(false)) {
97 WsTemplateRef templateRef = WsTemplateRef.fromRequest(wsRequest);
98 PermissionTemplateDto template = wsSupport.findTemplate(dbSession, templateRef);
99 checkGlobalAdmin(userSession);
101 PermissionQuery query = buildPermissionQuery(wsRequest);
102 int total = dbClient.permissionTemplateDao().countGroupNamesByQueryAndTemplate(dbSession, query, template.getUuid());
103 Paging paging = Paging.forPageIndex(wsRequest.mandatoryParamAsInt(PAGE)).withPageSize(wsRequest.mandatoryParamAsInt(PAGE_SIZE)).andTotal(total);
104 List<GroupDto> groups = findGroups(dbSession, query, template);
105 List<PermissionTemplateGroupDto> groupPermissions = findGroupPermissions(dbSession, groups, template);
106 Permissions.WsGroupsResponse groupsResponse = buildResponse(groups, groupPermissions, paging);
107 writeProtobuf(groupsResponse, wsRequest, wsResponse);
111 private PermissionQuery buildPermissionQuery(Request request) {
112 String textQuery = request.param(TEXT_QUERY);
113 String permission = request.param(PARAM_PERMISSION);
114 PermissionQuery.Builder permissionQuery = PermissionQuery.builder()
115 .setPermission(permission != null ? requestValidator.validateProjectPermission(permission) : null)
116 .setPageIndex(request.mandatoryParamAsInt(PAGE))
117 .setPageSize(request.mandatoryParamAsInt(PAGE_SIZE))
118 .setSearchQuery(textQuery);
119 return permissionQuery.build();
122 private static Permissions.WsGroupsResponse buildResponse(List<GroupDto> groups, List<PermissionTemplateGroupDto> groupPermissions, Paging paging) {
123 Multimap<String, String> permissionsByGroupUuid = TreeMultimap.create();
124 groupPermissions.forEach(groupPermission -> permissionsByGroupUuid.put(groupPermission.getGroupUuid(), groupPermission.getPermission()));
125 Permissions.WsGroupsResponse.Builder response = Permissions.WsGroupsResponse.newBuilder();
127 groups.forEach(group -> {
128 Permissions.Group.Builder wsGroup = response.addGroupsBuilder()
129 .setName(group.getName());
130 if (group.getUuid() != null) {
131 wsGroup.setId(String.valueOf(group.getUuid()));
133 ofNullable(group.getDescription()).ifPresent(wsGroup::setDescription);
134 wsGroup.addAllPermissions(permissionsByGroupUuid.get(group.getUuid()));
137 response.getPagingBuilder()
138 .setPageIndex(paging.pageIndex())
139 .setPageSize(paging.pageSize())
140 .setTotal(paging.total());
141 return response.build();
144 private List<GroupDto> findGroups(DbSession dbSession, PermissionQuery dbQuery, PermissionTemplateDto template) {
145 List<String> orderedNames = dbClient.permissionTemplateDao().selectGroupNamesByQueryAndTemplate(dbSession, dbQuery, template.getUuid());
146 List<GroupDto> groups = dbClient.groupDao().selectByNames(dbSession, orderedNames);
147 if (orderedNames.contains(DefaultGroups.ANYONE)) {
148 groups.add(0, new GroupDto().setUuid(DefaultGroups.ANYONE).setName(DefaultGroups.ANYONE));
150 return Ordering.explicit(orderedNames).onResultOf(GroupDto::getName).immutableSortedCopy(groups);
153 private List<PermissionTemplateGroupDto> findGroupPermissions(DbSession dbSession, List<GroupDto> groups, PermissionTemplateDto template) {
154 List<String> names = groups.stream().map(GroupDto::getName).collect(Collectors.toList());
155 return dbClient.permissionTemplateDao().selectGroupPermissionsByTemplateIdAndGroupNames(dbSession, template.getUuid(), names);