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 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2022 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.HashSet;
  23. import java.util.Map;
  24. import java.util.Objects;
  25. import java.util.Optional;
  26. import java.util.Set;
  27. import java.util.function.Function;
  28. import java.util.stream.Stream;
  29. import javax.annotation.CheckForNull;
  30. import javax.annotation.Nullable;
  31. import org.sonar.api.rule.RuleKey;
  32. import org.sonar.api.server.ws.Change;
  33. import org.sonar.api.server.ws.Request;
  34. import org.sonar.api.server.ws.Response;
  35. import org.sonar.api.server.ws.WebService;
  36. import org.sonar.api.web.UserRole;
  37. import org.sonar.core.util.Uuids;
  38. import org.sonar.db.DbClient;
  39. import org.sonar.db.DbSession;
  40. import org.sonar.db.component.ComponentDto;
  41. import org.sonar.db.issue.IssueDto;
  42. import org.sonar.db.protobuf.DbIssues;
  43. import org.sonar.db.protobuf.DbIssues.Locations;
  44. import org.sonar.db.rule.RuleDescriptionSectionDto;
  45. import org.sonar.db.rule.RuleDto;
  46. import org.sonar.db.user.UserDto;
  47. import org.sonar.markdown.Markdown;
  48. import org.sonar.server.exceptions.NotFoundException;
  49. import org.sonar.server.issue.IssueChangeWSSupport;
  50. import org.sonar.server.issue.IssueChangeWSSupport.FormattingContext;
  51. import org.sonar.server.issue.IssueChangeWSSupport.Load;
  52. import org.sonar.server.issue.TextRangeResponseFormatter;
  53. import org.sonar.server.issue.ws.UserResponseFormatter;
  54. import org.sonar.server.security.SecurityStandards;
  55. import org.sonarqube.ws.Common;
  56. import org.sonarqube.ws.Hotspots;
  57. import org.sonarqube.ws.Hotspots.ShowWsResponse;
  58. import static com.google.common.base.Preconditions.checkArgument;
  59. import static com.google.common.base.Strings.emptyToNull;
  60. import static com.google.common.base.Strings.nullToEmpty;
  61. import static com.google.common.collect.ImmutableSet.copyOf;
  62. import static com.google.common.collect.Sets.difference;
  63. import static java.lang.String.format;
  64. import static java.util.Collections.singleton;
  65. import static java.util.Optional.ofNullable;
  66. import static java.util.stream.Collectors.toMap;
  67. import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ASSESS_THE_PROBLEM_SECTION_KEY;
  68. import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.HOW_TO_FIX_SECTION_KEY;
  69. import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ROOT_CAUSE_SECTION_KEY;
  70. import static org.sonar.api.utils.DateUtils.formatDateTime;
  71. import static org.sonar.core.util.stream.MoreCollectors.toSet;
  72. import static org.sonar.db.rule.RuleDescriptionSectionDto.DEFAULT_KEY;
  73. import static org.sonar.server.ws.WsUtils.writeProtobuf;
  74. public class ShowAction implements HotspotsWsAction {
  75. private static final String PARAM_HOTSPOT_KEY = "hotspot";
  76. private final DbClient dbClient;
  77. private final HotspotWsSupport hotspotWsSupport;
  78. private final HotspotWsResponseFormatter responseFormatter;
  79. private final TextRangeResponseFormatter textRangeFormatter;
  80. private final UserResponseFormatter userFormatter;
  81. private final IssueChangeWSSupport issueChangeSupport;
  82. public ShowAction(DbClient dbClient, HotspotWsSupport hotspotWsSupport, HotspotWsResponseFormatter responseFormatter, TextRangeResponseFormatter textRangeFormatter,
  83. UserResponseFormatter userFormatter, IssueChangeWSSupport issueChangeSupport) {
  84. this.dbClient = dbClient;
  85. this.hotspotWsSupport = hotspotWsSupport;
  86. this.responseFormatter = responseFormatter;
  87. this.textRangeFormatter = textRangeFormatter;
  88. this.userFormatter = userFormatter;
  89. this.issueChangeSupport = issueChangeSupport;
  90. }
  91. @Override
  92. public void define(WebService.NewController controller) {
  93. WebService.NewAction action = controller
  94. .createAction("show")
  95. .setHandler(this)
  96. .setDescription("Provides the details of a Security Hotspot.")
  97. .setSince("8.1")
  98. .setChangelog(new Change("9.5", "The fields rule.riskDescription, rule.fixRecommendations, rule.vulnerabilityDescription of the response are deprecated."
  99. + " /api/rules/show endpoint should be used to fetch rule descriptions."));
  100. action.createParam(PARAM_HOTSPOT_KEY)
  101. .setDescription("Key of the Security Hotspot")
  102. .setExampleValue(Uuids.UUID_EXAMPLE_03)
  103. .setRequired(true);
  104. action.setResponseExample(getClass().getResource("show-example.json"));
  105. }
  106. @Override
  107. public void handle(Request request, Response response) throws Exception {
  108. String hotspotKey = request.mandatoryParam(PARAM_HOTSPOT_KEY);
  109. try (DbSession dbSession = dbClient.openSession(false)) {
  110. IssueDto hotspot = hotspotWsSupport.loadHotspot(dbSession, hotspotKey);
  111. Components components = loadComponents(dbSession, hotspot);
  112. Users users = loadUsers(dbSession, hotspot);
  113. RuleDto rule = loadRule(dbSession, hotspot);
  114. ShowWsResponse.Builder responseBuilder = ShowWsResponse.newBuilder();
  115. formatHotspot(responseBuilder, hotspot, users);
  116. formatComponents(components, responseBuilder);
  117. formatRule(responseBuilder, rule);
  118. formatTextRange(responseBuilder, hotspot);
  119. formatFlows(dbSession, responseBuilder, hotspot);
  120. FormattingContext formattingContext = formatChangeLogAndComments(dbSession, hotspot, users, components, responseBuilder);
  121. formatUsers(responseBuilder, users, formattingContext);
  122. writeProtobuf(responseBuilder.build(), request, response);
  123. }
  124. }
  125. private Users loadUsers(DbSession dbSession, IssueDto hotspot) {
  126. UserDto assignee = ofNullable(hotspot.getAssigneeUuid())
  127. .map(uuid -> dbClient.userDao().selectByUuid(dbSession, uuid))
  128. .orElse(null);
  129. UserDto author = ofNullable(hotspot.getAuthorLogin())
  130. .map(login -> {
  131. if (assignee != null && assignee.getLogin().equals(login)) {
  132. return assignee;
  133. }
  134. return dbClient.userDao().selectByLogin(dbSession, login);
  135. })
  136. .orElse(null);
  137. return new Users(assignee, author);
  138. }
  139. private static void formatHotspot(ShowWsResponse.Builder builder, IssueDto hotspot, Users users) {
  140. builder.setKey(hotspot.getKey());
  141. ofNullable(hotspot.getStatus()).ifPresent(builder::setStatus);
  142. ofNullable(hotspot.getResolution()).ifPresent(builder::setResolution);
  143. ofNullable(hotspot.getLine()).ifPresent(builder::setLine);
  144. ofNullable(emptyToNull(hotspot.getChecksum())).ifPresent(builder::setHash);
  145. builder.setMessage(nullToEmpty(hotspot.getMessage()));
  146. builder.setCreationDate(formatDateTime(hotspot.getIssueCreationDate()));
  147. builder.setUpdateDate(formatDateTime(hotspot.getIssueUpdateDate()));
  148. users.getAssignee().map(UserDto::getLogin).ifPresent(builder::setAssignee);
  149. Optional.ofNullable(hotspot.getAuthorLogin()).ifPresent(builder::setAuthor);
  150. }
  151. private void formatComponents(Components components, ShowWsResponse.Builder responseBuilder) {
  152. responseBuilder
  153. .setProject(responseFormatter.formatComponent(Hotspots.Component.newBuilder(), components.getProject()))
  154. .setComponent(responseFormatter.formatComponent(Hotspots.Component.newBuilder(), components.getComponent()));
  155. responseBuilder.setCanChangeStatus(hotspotWsSupport.canChangeStatus(components.getProject()));
  156. }
  157. private static void formatRule(ShowWsResponse.Builder responseBuilder, RuleDto ruleDto) {
  158. SecurityStandards securityStandards = SecurityStandards.fromSecurityStandards(ruleDto.getSecurityStandards());
  159. SecurityStandards.SQCategory sqCategory = securityStandards.getSqCategory();
  160. Hotspots.Rule.Builder ruleBuilder = Hotspots.Rule.newBuilder()
  161. .setKey(ruleDto.getKey().toString())
  162. .setName(nullToEmpty(ruleDto.getName()))
  163. .setSecurityCategory(sqCategory.getKey())
  164. .setVulnerabilityProbability(sqCategory.getVulnerability().name());
  165. Map<String, String> sectionKeyToContent = getSectionKeyToContent(ruleDto);
  166. Optional.ofNullable(sectionKeyToContent.get(DEFAULT_KEY)).ifPresent(ruleBuilder::setVulnerabilityDescription);
  167. Optional.ofNullable(sectionKeyToContent.get(ROOT_CAUSE_SECTION_KEY)).ifPresent(ruleBuilder::setVulnerabilityDescription);
  168. Optional.ofNullable(sectionKeyToContent.get(ASSESS_THE_PROBLEM_SECTION_KEY)).ifPresent(ruleBuilder::setRiskDescription);
  169. Optional.ofNullable(sectionKeyToContent.get(HOW_TO_FIX_SECTION_KEY)).ifPresent(ruleBuilder::setFixRecommendations);
  170. responseBuilder.setRule(ruleBuilder.build());
  171. }
  172. private static Map<String, String> getSectionKeyToContent(RuleDto ruleDefinitionDto) {
  173. return ruleDefinitionDto.getRuleDescriptionSectionDtos().stream()
  174. .collect(toMap(RuleDescriptionSectionDto::getKey,
  175. section -> getContentAndConvertToHtmlIfNecessary(ruleDefinitionDto.getDescriptionFormat(), section)));
  176. }
  177. private static String getContentAndConvertToHtmlIfNecessary(@Nullable RuleDto.Format descriptionFormat, RuleDescriptionSectionDto section) {
  178. if (RuleDto.Format.MARKDOWN.equals(descriptionFormat)) {
  179. return Markdown.convertToHtml(section.getContent());
  180. }
  181. return section.getContent();
  182. }
  183. private void formatTextRange(ShowWsResponse.Builder hotspotBuilder, IssueDto hotspot) {
  184. textRangeFormatter.formatTextRange(hotspot, hotspotBuilder::setTextRange);
  185. }
  186. private void formatFlows(DbSession dbSession, ShowWsResponse.Builder hotspotBuilder, IssueDto hotspot) {
  187. DbIssues.Locations locations = hotspot.parseLocations();
  188. if (locations == null) {
  189. return;
  190. }
  191. Set<String> componentUuids = readComponentUuidsFromLocations(hotspot, locations);
  192. Map<String, ComponentDto> componentsByUuids = loadComponents(dbSession, componentUuids);
  193. for (DbIssues.Flow flow : locations.getFlowList()) {
  194. Common.Flow.Builder targetFlow = Common.Flow.newBuilder();
  195. for (DbIssues.Location flowLocation : flow.getLocationList()) {
  196. targetFlow.addLocations(textRangeFormatter.formatLocation(flowLocation, hotspotBuilder.getComponent().getKey(), componentsByUuids));
  197. }
  198. hotspotBuilder.addFlows(targetFlow.build());
  199. }
  200. }
  201. private static Set<String> readComponentUuidsFromLocations(IssueDto hotspot, Locations locations) {
  202. Set<String> componentUuids = new HashSet<>();
  203. componentUuids.add(hotspot.getComponentUuid());
  204. for (DbIssues.Flow flow : locations.getFlowList()) {
  205. for (DbIssues.Location location : flow.getLocationList()) {
  206. if (location.hasComponentId()) {
  207. componentUuids.add(location.getComponentId());
  208. }
  209. }
  210. }
  211. return componentUuids;
  212. }
  213. private Map<String, ComponentDto> loadComponents(DbSession dbSession, Set<String> componentUuids) {
  214. Map<String, ComponentDto> componentsByUuids = dbClient.componentDao().selectSubProjectsByComponentUuids(dbSession,
  215. componentUuids)
  216. .stream()
  217. .collect(toMap(ComponentDto::uuid, Function.identity(), (componentDto, componentDto2) -> componentDto2));
  218. Set<String> componentUuidsToLoad = copyOf(difference(componentUuids, componentsByUuids.keySet()));
  219. if (!componentUuidsToLoad.isEmpty()) {
  220. dbClient.componentDao().selectByUuids(dbSession, componentUuidsToLoad)
  221. .forEach(c -> componentsByUuids.put(c.uuid(), c));
  222. }
  223. return componentsByUuids;
  224. }
  225. private FormattingContext formatChangeLogAndComments(DbSession dbSession, IssueDto hotspot, Users users, Components components, ShowWsResponse.Builder responseBuilder) {
  226. Set<UserDto> preloadedUsers = Stream.of(users.getAssignee(), users.getAuthor())
  227. .filter(Optional::isPresent)
  228. .map(Optional::get)
  229. .collect(toSet());
  230. Set<ComponentDto> preloadedComponents = ImmutableSet.of(components.project, components.component);
  231. FormattingContext formattingContext = issueChangeSupport
  232. .newFormattingContext(dbSession, singleton(hotspot), Load.ALL, preloadedUsers, preloadedComponents);
  233. issueChangeSupport.formatChangelog(hotspot, formattingContext)
  234. .forEach(responseBuilder::addChangelog);
  235. issueChangeSupport.formatComments(hotspot, Common.Comment.newBuilder(), formattingContext)
  236. .forEach(responseBuilder::addComment);
  237. return formattingContext;
  238. }
  239. private void formatUsers(ShowWsResponse.Builder responseBuilder, Users users, FormattingContext formattingContext) {
  240. Common.User.Builder userBuilder = Common.User.newBuilder();
  241. Stream.concat(
  242. Stream.of(users.getAssignee(), users.getAuthor())
  243. .filter(Optional::isPresent)
  244. .map(Optional::get),
  245. formattingContext.getUsers().stream())
  246. .distinct()
  247. .map(user -> userFormatter.formatUser(userBuilder, user))
  248. .forEach(responseBuilder::addUsers);
  249. }
  250. private RuleDto loadRule(DbSession dbSession, IssueDto hotspot) {
  251. RuleKey ruleKey = hotspot.getRuleKey();
  252. return dbClient.ruleDao().selectByKey(dbSession, ruleKey)
  253. .orElseThrow(() -> new NotFoundException(format("Rule '%s' does not exist", ruleKey)));
  254. }
  255. private Components loadComponents(DbSession dbSession, IssueDto hotspot) {
  256. String componentUuid = hotspot.getComponentUuid();
  257. ComponentDto project = hotspotWsSupport.loadAndCheckProject(dbSession, hotspot, UserRole.USER);
  258. checkArgument(componentUuid != null, "Hotspot '%s' has no component", hotspot.getKee());
  259. boolean hotspotOnProject = Objects.equals(project.uuid(), componentUuid);
  260. ComponentDto component = hotspotOnProject ? project
  261. : dbClient.componentDao().selectByUuid(dbSession, componentUuid)
  262. .orElseThrow(() -> new NotFoundException(format("Component with uuid '%s' does not exist", componentUuid)));
  263. return new Components(project, component);
  264. }
  265. private static final class Components {
  266. private final ComponentDto project;
  267. private final ComponentDto component;
  268. private Components(ComponentDto project, ComponentDto component) {
  269. this.project = project;
  270. this.component = component;
  271. }
  272. public ComponentDto getProject() {
  273. return project;
  274. }
  275. public ComponentDto getComponent() {
  276. return component;
  277. }
  278. }
  279. private static final class Users {
  280. @CheckForNull
  281. private final UserDto assignee;
  282. @CheckForNull
  283. private final UserDto author;
  284. private Users(@Nullable UserDto assignee, @Nullable UserDto author) {
  285. this.assignee = assignee;
  286. this.author = author;
  287. }
  288. public Optional<UserDto> getAssignee() {
  289. return ofNullable(assignee);
  290. }
  291. public Optional<UserDto> getAuthor() {
  292. return ofNullable(author);
  293. }
  294. }
  295. }