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

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