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.

GroupsAction.java 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2021 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.permission.ws;
  21. import com.google.common.collect.Multimap;
  22. import com.google.common.collect.Ordering;
  23. import com.google.common.collect.TreeMultimap;
  24. import com.google.common.io.Resources;
  25. import java.util.List;
  26. import java.util.Optional;
  27. import javax.annotation.Nullable;
  28. import org.sonar.api.security.DefaultGroups;
  29. import org.sonar.api.server.ws.Change;
  30. import org.sonar.api.server.ws.Request;
  31. import org.sonar.api.server.ws.Response;
  32. import org.sonar.api.server.ws.WebService;
  33. import org.sonar.api.server.ws.WebService.Param;
  34. import org.sonar.api.utils.Paging;
  35. import org.sonar.core.util.stream.MoreCollectors;
  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.PermissionQuery;
  41. import org.sonar.db.user.GroupDto;
  42. import org.sonar.server.user.UserSession;
  43. import org.sonarqube.ws.Permissions.Group;
  44. import org.sonarqube.ws.Permissions.WsGroupsResponse;
  45. import static java.util.Collections.emptyList;
  46. import static java.util.Optional.ofNullable;
  47. import static org.sonar.db.permission.PermissionQuery.DEFAULT_PAGE_SIZE;
  48. import static org.sonar.db.permission.PermissionQuery.RESULTS_MAX_SIZE;
  49. import static org.sonar.db.permission.PermissionQuery.SEARCH_QUERY_MIN_LENGTH;
  50. import static org.sonar.server.permission.ws.WsParameters.createProjectParameters;
  51. import static org.sonar.server.ws.WsUtils.writeProtobuf;
  52. import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
  53. public class GroupsAction implements PermissionsWsAction {
  54. private final DbClient dbClient;
  55. private final UserSession userSession;
  56. private final PermissionWsSupport wsSupport;
  57. private final WsParameters wsParameters;
  58. public GroupsAction(DbClient dbClient, UserSession userSession, PermissionWsSupport wsSupport, WsParameters wsParameters) {
  59. this.dbClient = dbClient;
  60. this.userSession = userSession;
  61. this.wsSupport = wsSupport;
  62. this.wsParameters = wsParameters;
  63. }
  64. @Override
  65. public void define(WebService.NewController context) {
  66. WebService.NewAction action = context.createAction("groups")
  67. .setSince("5.2")
  68. .setInternal(true)
  69. .setDescription("Lists the groups with their permissions.<br>" +
  70. "This service defaults to global permissions, but can be limited to project permissions by providing project id or project key.<br> " +
  71. "This service defaults to all groups, but can be limited to groups with a specific permission by providing the desired permission.<br>" +
  72. "Requires one of the following permissions:" +
  73. "<ul>" +
  74. "<li>'Administer System'</li>" +
  75. "<li>'Administer' rights on the specified project</li>" +
  76. "</ul>")
  77. .addPagingParams(DEFAULT_PAGE_SIZE, RESULTS_MAX_SIZE)
  78. .setChangelog(
  79. new Change("8.4", "Field 'id' in the response is deprecated. Format changes from integer to string."),
  80. new Change("7.4", "The response list is returning all groups even those without permissions, the groups with permission are at the top of the list."))
  81. .setResponseExample(Resources.getResource(getClass(), "groups-example.json"))
  82. .setHandler(this);
  83. action.createSearchQuery("sonar", "names")
  84. .setDescription("Limit search to group names that contain the supplied string.")
  85. .setMinimumLength(SEARCH_QUERY_MIN_LENGTH);
  86. wsParameters.createPermissionParameter(action).setRequired(false);
  87. createProjectParameters(action);
  88. }
  89. @Override
  90. public void handle(Request request, Response response) throws Exception {
  91. try (DbSession dbSession = dbClient.openSession(false)) {
  92. Optional<ComponentDto> project = wsSupport.findProject(dbSession, request);
  93. wsSupport.checkPermissionManagementAccess(userSession, project.orElse(null));
  94. PermissionQuery query = buildPermissionQuery(request, project.orElse(null));
  95. List<GroupDto> groups = findGroups(dbSession, query);
  96. int total = dbClient.groupPermissionDao().countGroupsByQuery(dbSession, query);
  97. List<GroupPermissionDto> groupsWithPermission = findGroupPermissions(dbSession, groups, project.orElse(null));
  98. Paging paging = Paging.forPageIndex(request.mandatoryParamAsInt(Param.PAGE)).withPageSize(query.getPageSize()).andTotal(total);
  99. WsGroupsResponse groupsResponse = buildResponse(groups, groupsWithPermission, paging);
  100. writeProtobuf(groupsResponse, request, response);
  101. }
  102. }
  103. private static PermissionQuery buildPermissionQuery(Request request, @Nullable ComponentDto project) {
  104. String textQuery = request.param(Param.TEXT_QUERY);
  105. PermissionQuery.Builder permissionQuery = PermissionQuery.builder()
  106. .setPermission(request.param(PARAM_PERMISSION))
  107. .setPageIndex(request.mandatoryParamAsInt(Param.PAGE))
  108. .setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE))
  109. .setSearchQuery(textQuery);
  110. if (project != null) {
  111. permissionQuery.setComponent(project.uuid());
  112. }
  113. return permissionQuery.build();
  114. }
  115. private static WsGroupsResponse buildResponse(List<GroupDto> groups, List<GroupPermissionDto> groupPermissions, Paging paging) {
  116. Multimap<String, String> permissionsByGroupUuid = TreeMultimap.create();
  117. groupPermissions.forEach(groupPermission -> permissionsByGroupUuid.put(groupPermission.getGroupUuid(), groupPermission.getRole()));
  118. WsGroupsResponse.Builder response = WsGroupsResponse.newBuilder();
  119. groups.forEach(group -> {
  120. Group.Builder wsGroup = response.addGroupsBuilder()
  121. .setName(group.getName());
  122. if (group.getUuid() != null) {
  123. wsGroup.setId(String.valueOf(group.getUuid()));
  124. }
  125. ofNullable(group.getDescription()).ifPresent(wsGroup::setDescription);
  126. wsGroup.addAllPermissions(permissionsByGroupUuid.get(group.getUuid()));
  127. });
  128. response.getPagingBuilder()
  129. .setPageIndex(paging.pageIndex())
  130. .setPageSize(paging.pageSize())
  131. .setTotal(paging.total());
  132. return response.build();
  133. }
  134. private List<GroupDto> findGroups(DbSession dbSession, PermissionQuery dbQuery) {
  135. List<String> orderedNames = dbClient.groupPermissionDao().selectGroupNamesByQuery(dbSession, dbQuery);
  136. List<GroupDto> groups = dbClient.groupDao().selectByNames(dbSession, orderedNames);
  137. if (orderedNames.contains(DefaultGroups.ANYONE)) {
  138. groups.add(0, new GroupDto().setUuid(DefaultGroups.ANYONE).setName(DefaultGroups.ANYONE));
  139. }
  140. return Ordering.explicit(orderedNames).onResultOf(GroupDto::getName).immutableSortedCopy(groups);
  141. }
  142. private List<GroupPermissionDto> findGroupPermissions(DbSession dbSession, List<GroupDto> groups, @Nullable ComponentDto project) {
  143. if (groups.isEmpty()) {
  144. return emptyList();
  145. }
  146. List<String> uuids = groups.stream().map(GroupDto::getUuid).collect(MoreCollectors.toList(groups.size()));
  147. return dbClient.groupPermissionDao().selectByGroupUuids(dbSession, uuids, project != null ? project.uuid() : null);
  148. }
  149. }