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.

ShowAction.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2020 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.hotspot.ws;
  21. import com.google.common.collect.ImmutableSet;
  22. import java.util.Objects;
  23. import java.util.Optional;
  24. import java.util.Set;
  25. import java.util.stream.Stream;
  26. import javax.annotation.CheckForNull;
  27. import javax.annotation.Nullable;
  28. import org.sonar.api.rule.RuleKey;
  29. import org.sonar.api.server.ws.Request;
  30. import org.sonar.api.server.ws.Response;
  31. import org.sonar.api.server.ws.WebService;
  32. import org.sonar.api.web.UserRole;
  33. import org.sonar.core.util.Uuids;
  34. import org.sonar.db.DbClient;
  35. import org.sonar.db.DbSession;
  36. import org.sonar.db.component.ComponentDto;
  37. import org.sonar.db.issue.IssueDto;
  38. import org.sonar.db.rule.RuleDefinitionDto;
  39. import org.sonar.db.user.UserDto;
  40. import org.sonar.server.exceptions.NotFoundException;
  41. import org.sonar.server.issue.IssueChangeWSSupport;
  42. import org.sonar.server.issue.IssueChangeWSSupport.FormattingContext;
  43. import org.sonar.server.issue.IssueChangeWSSupport.Load;
  44. import org.sonar.server.issue.TextRangeResponseFormatter;
  45. import org.sonar.server.issue.ws.UserResponseFormatter;
  46. import org.sonar.server.rule.HotspotRuleDescription;
  47. import org.sonar.server.security.SecurityStandards;
  48. import org.sonarqube.ws.Common;
  49. import org.sonarqube.ws.Hotspots;
  50. import org.sonarqube.ws.Hotspots.ShowWsResponse;
  51. import static com.google.common.base.Preconditions.checkArgument;
  52. import static com.google.common.base.Strings.nullToEmpty;
  53. import static java.lang.String.format;
  54. import static java.util.Collections.singleton;
  55. import static java.util.Optional.ofNullable;
  56. import static org.sonar.api.utils.DateUtils.formatDateTime;
  57. import static org.sonar.core.util.stream.MoreCollectors.toSet;
  58. import static org.sonar.server.ws.WsUtils.writeProtobuf;
  59. public class ShowAction implements HotspotsWsAction {
  60. private static final String PARAM_HOTSPOT_KEY = "hotspot";
  61. private final DbClient dbClient;
  62. private final HotspotWsSupport hotspotWsSupport;
  63. private final HotspotWsResponseFormatter responseFormatter;
  64. private final TextRangeResponseFormatter textRangeFormatter;
  65. private final UserResponseFormatter userFormatter;
  66. private final IssueChangeWSSupport issueChangeSupport;
  67. public ShowAction(DbClient dbClient, HotspotWsSupport hotspotWsSupport,
  68. HotspotWsResponseFormatter responseFormatter, TextRangeResponseFormatter textRangeFormatter,
  69. UserResponseFormatter userFormatter, IssueChangeWSSupport issueChangeSupport) {
  70. this.dbClient = dbClient;
  71. this.hotspotWsSupport = hotspotWsSupport;
  72. this.responseFormatter = responseFormatter;
  73. this.textRangeFormatter = textRangeFormatter;
  74. this.userFormatter = userFormatter;
  75. this.issueChangeSupport = issueChangeSupport;
  76. }
  77. @Override
  78. public void define(WebService.NewController controller) {
  79. WebService.NewAction action = controller
  80. .createAction("show")
  81. .setHandler(this)
  82. .setDescription("Provides the details of a Security Hotspot.")
  83. .setSince("8.1")
  84. .setInternal(true);
  85. action.createParam(PARAM_HOTSPOT_KEY)
  86. .setDescription("Key of the Security Hotspot")
  87. .setExampleValue(Uuids.UUID_EXAMPLE_03)
  88. .setRequired(true);
  89. action.setResponseExample(getClass().getResource("show-example.json"));
  90. }
  91. @Override
  92. public void handle(Request request, Response response) throws Exception {
  93. String hotspotKey = request.mandatoryParam(PARAM_HOTSPOT_KEY);
  94. try (DbSession dbSession = dbClient.openSession(false)) {
  95. IssueDto hotspot = hotspotWsSupport.loadHotspot(dbSession, hotspotKey);
  96. Components components = loadComponents(dbSession, hotspot);
  97. Users users = loadUsers(dbSession, hotspot);
  98. RuleDefinitionDto rule = loadRule(dbSession, hotspot);
  99. ShowWsResponse.Builder responseBuilder = ShowWsResponse.newBuilder();
  100. formatHotspot(responseBuilder, hotspot, users);
  101. formatComponents(components, responseBuilder);
  102. formatRule(responseBuilder, rule);
  103. formatTextRange(responseBuilder, hotspot);
  104. FormattingContext formattingContext = formatChangeLogAndComments(dbSession, hotspot, users, components, responseBuilder);
  105. formatUsers(responseBuilder, users, formattingContext);
  106. writeProtobuf(responseBuilder.build(), request, response);
  107. }
  108. }
  109. private Users loadUsers(DbSession dbSession, IssueDto hotspot) {
  110. UserDto assignee = ofNullable(hotspot.getAssigneeUuid())
  111. .map(uuid -> dbClient.userDao().selectByUuid(dbSession, uuid))
  112. .orElse(null);
  113. UserDto author = ofNullable(hotspot.getAuthorLogin())
  114. .map(login -> {
  115. if (assignee != null && assignee.getLogin().equals(login)) {
  116. return assignee;
  117. }
  118. return dbClient.userDao().selectByLogin(dbSession, login);
  119. })
  120. .orElse(null);
  121. return new Users(assignee, author);
  122. }
  123. private void formatHotspot(ShowWsResponse.Builder builder, IssueDto hotspot, Users users) {
  124. builder.setKey(hotspot.getKey());
  125. ofNullable(hotspot.getStatus()).ifPresent(builder::setStatus);
  126. ofNullable(hotspot.getResolution()).ifPresent(builder::setResolution);
  127. ofNullable(hotspot.getLine()).ifPresent(builder::setLine);
  128. builder.setMessage(nullToEmpty(hotspot.getMessage()));
  129. builder.setCreationDate(formatDateTime(hotspot.getIssueCreationDate()));
  130. builder.setUpdateDate(formatDateTime(hotspot.getIssueUpdateDate()));
  131. users.getAssignee().map(UserDto::getLogin).ifPresent(builder::setAssignee);
  132. Optional.ofNullable(hotspot.getAuthorLogin()).ifPresent(builder::setAuthor);
  133. }
  134. private void formatComponents(Components components, ShowWsResponse.Builder responseBuilder) {
  135. responseBuilder
  136. .setProject(responseFormatter.formatComponent(Hotspots.Component.newBuilder(), components.getProject()))
  137. .setComponent(responseFormatter.formatComponent(Hotspots.Component.newBuilder(), components.getComponent()));
  138. responseBuilder.setCanChangeStatus(hotspotWsSupport.canChangeStatus(components.getProject()));
  139. }
  140. private void formatRule(ShowWsResponse.Builder responseBuilder, RuleDefinitionDto ruleDefinitionDto) {
  141. SecurityStandards securityStandards = SecurityStandards.fromSecurityStandards(ruleDefinitionDto.getSecurityStandards());
  142. SecurityStandards.SQCategory sqCategory = securityStandards.getSqCategory();
  143. HotspotRuleDescription hotspotRuleDescription = HotspotRuleDescription.from(ruleDefinitionDto);
  144. Hotspots.Rule.Builder ruleBuilder = Hotspots.Rule.newBuilder()
  145. .setKey(ruleDefinitionDto.getKey().toString())
  146. .setName(nullToEmpty(ruleDefinitionDto.getName()))
  147. .setSecurityCategory(sqCategory.getKey())
  148. .setVulnerabilityProbability(sqCategory.getVulnerability().name());
  149. hotspotRuleDescription.getVulnerable().ifPresent(ruleBuilder::setVulnerabilityDescription);
  150. hotspotRuleDescription.getRisk().ifPresent(ruleBuilder::setRiskDescription);
  151. hotspotRuleDescription.getFixIt().ifPresent(ruleBuilder::setFixRecommendations);
  152. responseBuilder.setRule(ruleBuilder.build());
  153. }
  154. private void formatTextRange(ShowWsResponse.Builder responseBuilder, IssueDto hotspot) {
  155. textRangeFormatter.formatTextRange(hotspot, responseBuilder::setTextRange);
  156. }
  157. private FormattingContext formatChangeLogAndComments(DbSession dbSession, IssueDto hotspot, Users users, Components components, ShowWsResponse.Builder responseBuilder) {
  158. Set<UserDto> preloadedUsers = Stream.of(users.getAssignee(), users.getAuthor())
  159. .filter(Optional::isPresent)
  160. .map(Optional::get)
  161. .collect(toSet());
  162. Set<ComponentDto> preloadedComponents = ImmutableSet.of(components.project, components.component);
  163. FormattingContext formattingContext = issueChangeSupport
  164. .newFormattingContext(dbSession, singleton(hotspot), Load.ALL, preloadedUsers, preloadedComponents);
  165. issueChangeSupport.formatChangelog(hotspot, formattingContext)
  166. .forEach(responseBuilder::addChangelog);
  167. issueChangeSupport.formatComments(hotspot, Common.Comment.newBuilder(), formattingContext)
  168. .forEach(responseBuilder::addComment);
  169. return formattingContext;
  170. }
  171. private void formatUsers(ShowWsResponse.Builder responseBuilder, Users users, FormattingContext formattingContext) {
  172. Common.User.Builder userBuilder = Common.User.newBuilder();
  173. Stream.concat(
  174. Stream.of(users.getAssignee(), users.getAuthor())
  175. .filter(Optional::isPresent)
  176. .map(Optional::get),
  177. formattingContext.getUsers().stream())
  178. .distinct()
  179. .map(user -> userFormatter.formatUser(userBuilder, user))
  180. .forEach(responseBuilder::addUsers);
  181. }
  182. private RuleDefinitionDto loadRule(DbSession dbSession, IssueDto hotspot) {
  183. RuleKey ruleKey = hotspot.getRuleKey();
  184. return dbClient.ruleDao().selectDefinitionByKey(dbSession, ruleKey)
  185. .orElseThrow(() -> new NotFoundException(format("Rule '%s' does not exist", ruleKey)));
  186. }
  187. private Components loadComponents(DbSession dbSession, IssueDto hotspot) {
  188. String componentUuid = hotspot.getComponentUuid();
  189. ComponentDto project = hotspotWsSupport.loadAndCheckProject(dbSession, hotspot, UserRole.USER);
  190. checkArgument(componentUuid != null, "Hotspot '%s' has no component", hotspot.getKee());
  191. boolean hotspotOnProject = Objects.equals(project.uuid(), componentUuid);
  192. ComponentDto component = hotspotOnProject ? project
  193. : dbClient.componentDao().selectByUuid(dbSession, componentUuid)
  194. .orElseThrow(() -> new NotFoundException(format("Component with uuid '%s' does not exist", componentUuid)));
  195. return new Components(project, component);
  196. }
  197. private static final class Components {
  198. private final ComponentDto project;
  199. private final ComponentDto component;
  200. private Components(ComponentDto project, ComponentDto component) {
  201. this.project = project;
  202. this.component = component;
  203. }
  204. public ComponentDto getProject() {
  205. return project;
  206. }
  207. public ComponentDto getComponent() {
  208. return component;
  209. }
  210. }
  211. private static final class Users {
  212. @CheckForNull
  213. private final UserDto assignee;
  214. @CheckForNull
  215. private final UserDto author;
  216. private Users(@Nullable UserDto assignee, @Nullable UserDto author) {
  217. this.assignee = assignee;
  218. this.author = author;
  219. }
  220. public Optional<UserDto> getAssignee() {
  221. return ofNullable(assignee);
  222. }
  223. public Optional<UserDto> getAuthor() {
  224. return ofNullable(author);
  225. }
  226. }
  227. }