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

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