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.

SearchAction.java 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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.issue.ws;
  21. import com.google.common.collect.ImmutableList;
  22. import com.google.common.collect.Lists;
  23. import java.util.ArrayList;
  24. import java.util.Arrays;
  25. import java.util.EnumSet;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.Optional;
  29. import java.util.Set;
  30. import java.util.stream.Collectors;
  31. import javax.annotation.Nullable;
  32. import org.elasticsearch.action.search.SearchResponse;
  33. import org.elasticsearch.search.SearchHit;
  34. import org.sonar.api.rule.Severity;
  35. import org.sonar.api.rules.RuleType;
  36. import org.sonar.api.server.ws.Change;
  37. import org.sonar.api.server.ws.Request;
  38. import org.sonar.api.server.ws.Response;
  39. import org.sonar.api.server.ws.WebService;
  40. import org.sonar.api.server.ws.WebService.Param;
  41. import org.sonar.api.utils.Paging;
  42. import org.sonar.api.utils.System2;
  43. import org.sonar.core.util.stream.MoreCollectors;
  44. import org.sonar.db.DbClient;
  45. import org.sonar.db.DbSession;
  46. import org.sonar.db.user.UserDto;
  47. import org.sonar.server.es.Facets;
  48. import org.sonar.server.es.SearchOptions;
  49. import org.sonar.server.issue.SearchRequest;
  50. import org.sonar.server.issue.index.IssueIndex;
  51. import org.sonar.server.issue.index.IssueIndexSyncProgressChecker;
  52. import org.sonar.server.issue.index.IssueQuery;
  53. import org.sonar.server.issue.index.IssueQueryFactory;
  54. import org.sonar.server.issue.index.IssueScope;
  55. import org.sonar.server.security.SecurityStandards.SQCategory;
  56. import org.sonar.server.user.UserSession;
  57. import org.sonarqube.ws.Issues.SearchWsResponse;
  58. import static com.google.common.base.MoreObjects.firstNonNull;
  59. import static com.google.common.base.Preconditions.checkArgument;
  60. import static com.google.common.collect.Iterables.concat;
  61. import static com.google.common.collect.Sets.newHashSet;
  62. import static java.lang.String.format;
  63. import static java.util.Collections.emptyList;
  64. import static java.util.Collections.singletonList;
  65. import static java.util.Optional.ofNullable;
  66. import static java.util.stream.Collectors.toList;
  67. import static org.sonar.api.issue.Issue.RESOLUTIONS;
  68. import static org.sonar.api.issue.Issue.RESOLUTION_FIXED;
  69. import static org.sonar.api.issue.Issue.RESOLUTION_REMOVED;
  70. import static org.sonar.api.issue.Issue.STATUS_IN_REVIEW;
  71. import static org.sonar.api.issue.Issue.STATUS_OPEN;
  72. import static org.sonar.api.issue.Issue.STATUS_REOPENED;
  73. import static org.sonar.api.issue.Issue.STATUS_REVIEWED;
  74. import static org.sonar.api.issue.Issue.STATUS_TO_REVIEW;
  75. import static org.sonar.api.server.ws.WebService.Param.FACETS;
  76. import static org.sonar.api.utils.Paging.forPageIndex;
  77. import static org.sonar.core.util.stream.MoreCollectors.toSet;
  78. import static org.sonar.server.es.SearchOptions.MAX_PAGE_SIZE;
  79. import static org.sonar.server.issue.index.IssueIndex.FACET_ASSIGNED_TO_ME;
  80. import static org.sonar.server.issue.index.IssueIndex.FACET_PROJECTS;
  81. import static org.sonar.server.issue.index.IssueQuery.SORT_BY_ASSIGNEE;
  82. import static org.sonar.server.issue.index.IssueQueryFactory.ISSUE_STATUSES;
  83. import static org.sonar.server.issue.index.IssueQueryFactory.UNKNOWN;
  84. import static org.sonar.server.security.SecurityStandards.SANS_TOP_25_INSECURE_INTERACTION;
  85. import static org.sonar.server.security.SecurityStandards.SANS_TOP_25_POROUS_DEFENSES;
  86. import static org.sonar.server.security.SecurityStandards.SANS_TOP_25_RISKY_RESOURCE;
  87. import static org.sonar.server.security.SecurityStandards.UNKNOWN_STANDARD;
  88. import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001;
  89. import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
  90. import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001;
  91. import static org.sonar.server.ws.WsUtils.writeProtobuf;
  92. import static org.sonarqube.ws.client.issue.IssuesWsParameters.ACTION_SEARCH;
  93. import static org.sonarqube.ws.client.issue.IssuesWsParameters.DEPRECATED_PARAM_AUTHORS;
  94. import static org.sonarqube.ws.client.issue.IssuesWsParameters.FACET_MODE;
  95. import static org.sonarqube.ws.client.issue.IssuesWsParameters.FACET_MODE_COUNT;
  96. import static org.sonarqube.ws.client.issue.IssuesWsParameters.FACET_MODE_EFFORT;
  97. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ADDITIONAL_FIELDS;
  98. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ASC;
  99. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ASSIGNED;
  100. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ASSIGNEES;
  101. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_AUTHOR;
  102. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_BRANCH;
  103. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_COMPONENT_KEYS;
  104. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CREATED_AFTER;
  105. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CREATED_AT;
  106. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CREATED_BEFORE;
  107. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CREATED_IN_LAST;
  108. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_CWE;
  109. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_DIRECTORIES;
  110. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_FILES;
  111. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ISSUES;
  112. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_LANGUAGES;
  113. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_MODULE_UUIDS;
  114. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_ON_COMPONENT_ONLY;
  115. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_OWASP_TOP_10;
  116. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_PROJECTS;
  117. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_PULL_REQUEST;
  118. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_RESOLUTIONS;
  119. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_RESOLVED;
  120. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_RULES;
  121. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SANS_TOP_25;
  122. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SCOPES;
  123. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SEVERITIES;
  124. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SINCE_LEAK_PERIOD;
  125. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SONARSOURCE_SECURITY;
  126. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_STATUSES;
  127. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_TAGS;
  128. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_TIMEZONE;
  129. import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_TYPES;
  130. public class SearchAction implements IssuesWsAction {
  131. private static final String LOGIN_MYSELF = "__me__";
  132. private static final Set<String> ISSUE_SCOPES = Arrays.stream(IssueScope.values()).map(Enum::name).collect(Collectors.toSet());
  133. private static final EnumSet<RuleType> ALL_RULE_TYPES_EXCEPT_SECURITY_HOTSPOTS = EnumSet.complementOf(EnumSet.of(RuleType.SECURITY_HOTSPOT));
  134. static final List<String> SUPPORTED_FACETS = ImmutableList.of(
  135. FACET_PROJECTS,
  136. PARAM_MODULE_UUIDS,
  137. PARAM_FILES,
  138. FACET_ASSIGNED_TO_ME,
  139. PARAM_SEVERITIES,
  140. PARAM_STATUSES,
  141. PARAM_RESOLUTIONS,
  142. PARAM_RULES,
  143. PARAM_ASSIGNEES,
  144. DEPRECATED_PARAM_AUTHORS,
  145. PARAM_AUTHOR,
  146. PARAM_DIRECTORIES,
  147. PARAM_SCOPES,
  148. PARAM_LANGUAGES,
  149. PARAM_TAGS,
  150. PARAM_TYPES,
  151. PARAM_OWASP_TOP_10,
  152. PARAM_SANS_TOP_25,
  153. PARAM_CWE,
  154. PARAM_CREATED_AT,
  155. PARAM_SONARSOURCE_SECURITY);
  156. private static final String INTERNAL_PARAMETER_DISCLAIMER = "This parameter is mostly used by the Issues page, please prefer usage of the componentKeys parameter. ";
  157. private static final Set<String> FACETS_REQUIRING_PROJECT = newHashSet(PARAM_MODULE_UUIDS, PARAM_FILES, PARAM_DIRECTORIES);
  158. private final UserSession userSession;
  159. private final IssueIndex issueIndex;
  160. private final IssueQueryFactory issueQueryFactory;
  161. private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker;
  162. private final SearchResponseLoader searchResponseLoader;
  163. private final SearchResponseFormat searchResponseFormat;
  164. private final System2 system2;
  165. private final DbClient dbClient;
  166. public SearchAction(UserSession userSession, IssueIndex issueIndex, IssueQueryFactory issueQueryFactory, IssueIndexSyncProgressChecker issueIndexSyncProgressChecker,
  167. SearchResponseLoader searchResponseLoader, SearchResponseFormat searchResponseFormat, System2 system2, DbClient dbClient) {
  168. this.userSession = userSession;
  169. this.issueIndex = issueIndex;
  170. this.issueQueryFactory = issueQueryFactory;
  171. this.issueIndexSyncProgressChecker = issueIndexSyncProgressChecker;
  172. this.searchResponseLoader = searchResponseLoader;
  173. this.searchResponseFormat = searchResponseFormat;
  174. this.system2 = system2;
  175. this.dbClient = dbClient;
  176. }
  177. @Override
  178. public void define(WebService.NewController controller) {
  179. WebService.NewAction action = controller
  180. .createAction(ACTION_SEARCH)
  181. .setHandler(this)
  182. .setDescription("Search for issues.<br>Requires the 'Browse' permission on the specified project(s)."
  183. + "<br/>When issue indexation is in progress returns 503 service unavailable HTTP code.")
  184. .setSince("3.6")
  185. .setChangelog(
  186. new Change("8.6", "Parameter 'timeZone' added"),
  187. new Change("8.5", "Facet 'fileUuids' is dropped in favour of the new facet 'files'" +
  188. "Note that they are not strictly identical, the latter returns the file paths."),
  189. new Change("8.5", "Internal parameter 'fileUuids' has been dropped"),
  190. new Change("8.4", "parameters 'componentUuids', 'projectKeys' has been dropped."),
  191. new Change("8.2", "'REVIEWED', 'TO_REVIEW' status param values are no longer supported"),
  192. new Change("8.2", "Security hotspots are no longer returned as type 'SECURITY_HOTSPOT' is not supported anymore, use dedicated api/hotspots"),
  193. new Change("8.2", "response field 'fromHotspot' has been deprecated and is no more populated"),
  194. new Change("8.2", "Status 'IN_REVIEW' for Security Hotspots has been deprecated"),
  195. new Change("7.8", format("added new Security Hotspots statuses : %s, %s and %s", STATUS_TO_REVIEW, STATUS_IN_REVIEW, STATUS_REVIEWED)),
  196. new Change("7.8", "Security hotspots are returned by default"),
  197. new Change("7.7", format("Value '%s' in parameter '%s' is deprecated, please use '%s' instead", DEPRECATED_PARAM_AUTHORS, FACETS, PARAM_AUTHOR)),
  198. new Change("7.6", format("The use of module keys in parameter '%s' is deprecated", PARAM_COMPONENT_KEYS)),
  199. new Change("7.4", "The facet 'projectUuids' is dropped in favour of the new facet 'projects'. " +
  200. "Note that they are not strictly identical, the latter returns the project keys."),
  201. new Change("7.4", format("Parameter '%s' does not accept anymore deprecated value 'debt'", FACET_MODE)),
  202. new Change("7.3", "response field 'fromHotspot' added to issues that are security hotspots"),
  203. new Change("7.3", "added facets 'sansTop25', 'owaspTop10' and 'cwe'"),
  204. new Change("7.2", "response field 'externalRuleEngine' added to issues that have been imported from an external rule engine"),
  205. new Change("7.2", format("value '%s' in parameter '%s' is deprecated, it won't have any effect", SORT_BY_ASSIGNEE, Param.SORT)),
  206. new Change("6.5", "parameters 'projects', 'projectUuids', 'moduleUuids', 'directories', 'fileUuids' are marked as internal"),
  207. new Change("6.3", "response field 'email' is renamed 'avatar'"),
  208. new Change("5.5", "response fields 'reporter' and 'actionPlan' are removed (drop of action plan and manual issue features)"),
  209. new Change("5.5", "parameters 'reporters', 'actionPlans' and 'planned' are dropped and therefore ignored (drop of action plan and manual issue features)"),
  210. new Change("5.5", "response field 'debt' is renamed 'effort'"))
  211. .setResponseExample(getClass().getResource("search-example.json"));
  212. action.addPagingParams(100, MAX_PAGE_SIZE);
  213. action.createParam(FACETS)
  214. .setDescription("Comma-separated list of the facets to be computed. No facet is computed by default.")
  215. .setPossibleValues(SUPPORTED_FACETS);
  216. action.createParam(FACET_MODE)
  217. .setDefaultValue(FACET_MODE_COUNT)
  218. .setDeprecatedSince("7.9")
  219. .setDescription("Choose the returned value for facet items, either count of issues or sum of remediation effort.")
  220. .setPossibleValues(FACET_MODE_COUNT, FACET_MODE_EFFORT);
  221. action.addSortParams(IssueQuery.SORTS, null, true);
  222. action.createParam(PARAM_ADDITIONAL_FIELDS)
  223. .setSince("5.2")
  224. .setDescription("Comma-separated list of the optional fields to be returned in response. Action plans are dropped in 5.5, it is not returned in the response.")
  225. .setPossibleValues(SearchAdditionalField.possibleValues());
  226. addComponentRelatedParams(action);
  227. action.createParam(PARAM_ISSUES)
  228. .setDescription("Comma-separated list of issue keys")
  229. .setExampleValue("5bccd6e8-f525-43a2-8d76-fcb13dde79ef");
  230. action.createParam(PARAM_SEVERITIES)
  231. .setDescription("Comma-separated list of severities")
  232. .setExampleValue(Severity.BLOCKER + "," + Severity.CRITICAL)
  233. .setPossibleValues(Severity.ALL);
  234. action.createParam(PARAM_STATUSES)
  235. .setDescription("Comma-separated list of statuses")
  236. .setExampleValue(STATUS_OPEN + "," + STATUS_REOPENED)
  237. .setPossibleValues(ISSUE_STATUSES);
  238. action.createParam(PARAM_RESOLUTIONS)
  239. .setDescription("Comma-separated list of resolutions")
  240. .setExampleValue(RESOLUTION_FIXED + "," + RESOLUTION_REMOVED)
  241. .setPossibleValues(RESOLUTIONS);
  242. action.createParam(PARAM_RESOLVED)
  243. .setDescription("To match resolved or unresolved issues")
  244. .setBooleanPossibleValues();
  245. action.createParam(PARAM_RULES)
  246. .setDescription("Comma-separated list of coding rule keys. Format is &lt;repository&gt;:&lt;rule&gt;")
  247. .setExampleValue("squid:AvoidCycles");
  248. action.createParam(PARAM_TAGS)
  249. .setDescription("Comma-separated list of tags.")
  250. .setExampleValue("security,convention");
  251. action.createParam(PARAM_TYPES)
  252. .setDescription("Comma-separated list of types.")
  253. .setSince("5.5")
  254. .setPossibleValues(ALL_RULE_TYPES_EXCEPT_SECURITY_HOTSPOTS)
  255. .setExampleValue(format("%s,%s", RuleType.CODE_SMELL, RuleType.BUG));
  256. action.createParam(PARAM_OWASP_TOP_10)
  257. .setDescription("Comma-separated list of OWASP Top 10 lowercase categories.")
  258. .setSince("7.3")
  259. .setPossibleValues("a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10");
  260. action.createParam(PARAM_SANS_TOP_25)
  261. .setDescription("Comma-separated list of SANS Top 25 categories.")
  262. .setSince("7.3")
  263. .setPossibleValues(SANS_TOP_25_INSECURE_INTERACTION, SANS_TOP_25_RISKY_RESOURCE, SANS_TOP_25_POROUS_DEFENSES);
  264. action.createParam(PARAM_CWE)
  265. .setDescription("Comma-separated list of CWE identifiers. Use '" + UNKNOWN_STANDARD + "' to select issues not associated to any CWE.")
  266. .setExampleValue("12,125," + UNKNOWN_STANDARD);
  267. action.createParam(PARAM_SONARSOURCE_SECURITY)
  268. .setDescription("Comma-separated list of SonarSource security categories. Use '" + SQCategory.OTHERS.getKey() + "' to select issues not associated" +
  269. " with any category")
  270. .setSince("7.8")
  271. .setPossibleValues(Arrays.stream(SQCategory.values()).map(SQCategory::getKey).collect(Collectors.toList()));
  272. action.createParam(DEPRECATED_PARAM_AUTHORS)
  273. .setDeprecatedSince("7.7")
  274. .setDescription("This parameter is deprecated, please use '%s' instead", PARAM_AUTHOR)
  275. .setExampleValue("torvalds@linux-foundation.org");
  276. action.createParam(PARAM_AUTHOR)
  277. .setDescription("SCM accounts. To set several values, the parameter must be called once for each value.")
  278. .setExampleValue("author=torvalds@linux-foundation.org&author=linux@fondation.org");
  279. action.createParam(PARAM_ASSIGNEES)
  280. .setDescription("Comma-separated list of assignee logins. The value '__me__' can be used as a placeholder for user who performs the request")
  281. .setExampleValue("admin,usera,__me__");
  282. action.createParam(PARAM_ASSIGNED)
  283. .setDescription("To retrieve assigned or unassigned issues")
  284. .setBooleanPossibleValues();
  285. action.createParam(PARAM_SCOPES)
  286. .setDescription("Comma-separated list of scopes. Available since 8.5")
  287. .setPossibleValues(IssueScope.MAIN.name(), IssueScope.TEST.name())
  288. .setExampleValue(format("%s,%s", IssueScope.MAIN.name(), IssueScope.TEST.name()));
  289. action.createParam(PARAM_LANGUAGES)
  290. .setDescription("Comma-separated list of languages. Available since 4.4")
  291. .setExampleValue("java,js");
  292. action.createParam(PARAM_CREATED_AT)
  293. .setDescription("Datetime to retrieve issues created during a specific analysis")
  294. .setExampleValue("2017-10-19T13:00:00+0200");
  295. action.createParam(PARAM_CREATED_AFTER)
  296. .setDescription("To retrieve issues created after the given date (inclusive). <br>" +
  297. "Either a date (use '" + PARAM_TIMEZONE + "' attribute or it will default to server timezone) or datetime can be provided. <br>" +
  298. "If this parameter is set, createdInLast must not be set")
  299. .setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
  300. action.createParam(PARAM_CREATED_BEFORE)
  301. .setDescription("To retrieve issues created before the given date (exclusive). <br>" +
  302. "Either a date (use '" + PARAM_TIMEZONE + "' attribute or it will default to server timezone) or datetime can be provided.")
  303. .setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
  304. action.createParam(PARAM_CREATED_IN_LAST)
  305. .setDescription("To retrieve issues created during a time span before the current time (exclusive). " +
  306. "Accepted units are 'y' for year, 'm' for month, 'w' for week and 'd' for day. " +
  307. "If this parameter is set, createdAfter must not be set")
  308. .setExampleValue("1m2w (1 month 2 weeks)");
  309. action.createParam(PARAM_SINCE_LEAK_PERIOD)
  310. .setDescription("To retrieve issues created since the leak period.<br>" +
  311. "If this parameter is set to a truthy value, createdAfter must not be set and one component uuid or key must be provided.")
  312. .setBooleanPossibleValues()
  313. .setDefaultValue("false");
  314. action.createParam(PARAM_TIMEZONE)
  315. .setDescription(
  316. "To resolve dates passed to '" + PARAM_CREATED_AFTER + "' or '" + PARAM_CREATED_BEFORE + "' (does not apply to datetime) and to compute creation date histogram")
  317. .setRequired(false)
  318. .setExampleValue("'Europe/Paris', 'Z' or '+02:00'")
  319. .setSince("8.6");
  320. }
  321. private static void addComponentRelatedParams(WebService.NewAction action) {
  322. action.createParam(PARAM_ON_COMPONENT_ONLY)
  323. .setDescription("Return only issues at a component's level, not on its descendants (modules, directories, files, etc). " +
  324. "This parameter is only considered when componentKeys is set.")
  325. .setBooleanPossibleValues()
  326. .setDefaultValue("false");
  327. action.createParam(PARAM_COMPONENT_KEYS)
  328. .setDescription("Comma-separated list of component keys. Retrieve issues associated to a specific list of components (and all its descendants). " +
  329. "A component can be a portfolio, project, module, directory or file.")
  330. .setExampleValue(KEY_PROJECT_EXAMPLE_001);
  331. action.createParam(PARAM_PROJECTS)
  332. .setDescription("To retrieve issues associated to a specific list of projects (comma-separated list of project keys). " +
  333. INTERNAL_PARAMETER_DISCLAIMER +
  334. "If this parameter is set, projectUuids must not be set.")
  335. .setInternal(true)
  336. .setExampleValue(KEY_PROJECT_EXAMPLE_001);
  337. action.createParam(PARAM_MODULE_UUIDS)
  338. .setDescription("To retrieve issues associated to a specific list of modules (comma-separated list of module IDs). " +
  339. INTERNAL_PARAMETER_DISCLAIMER)
  340. .setInternal(true)
  341. .setDeprecatedSince("7.6")
  342. .setExampleValue("7d8749e8-3070-4903-9188-bdd82933bb92");
  343. action.createParam(PARAM_DIRECTORIES)
  344. .setDescription("To retrieve issues associated to a specific list of directories (comma-separated list of directory paths). " +
  345. "This parameter is only meaningful when a module is selected. " +
  346. INTERNAL_PARAMETER_DISCLAIMER)
  347. .setInternal(true)
  348. .setSince("5.1")
  349. .setExampleValue("src/main/java/org/sonar/server/");
  350. action.createParam(PARAM_FILES)
  351. .setDescription("To retrieve issues associated to a specific list of files (comma-separated list of file paths). " +
  352. INTERNAL_PARAMETER_DISCLAIMER)
  353. .setInternal(true)
  354. .setExampleValue("src/main/java/org/sonar/server/Test.java");
  355. action.createParam(PARAM_BRANCH)
  356. .setDescription("Branch key. Not available in the community edition.")
  357. .setExampleValue(KEY_BRANCH_EXAMPLE_001)
  358. .setSince("6.6");
  359. action.createParam(PARAM_PULL_REQUEST)
  360. .setDescription("Pull request id. Not available in the community edition.")
  361. .setExampleValue(KEY_PULL_REQUEST_EXAMPLE_001)
  362. .setSince("7.1");
  363. }
  364. @Override
  365. public final void handle(Request request, Response response) {
  366. try (DbSession dbSession = dbClient.openSession(false)) {
  367. SearchRequest searchRequest = toSearchWsRequest(dbSession, request);
  368. checkIfNeedIssueSync(dbSession, searchRequest);
  369. SearchWsResponse searchWsResponse = doHandle(searchRequest);
  370. writeProtobuf(searchWsResponse, request, response);
  371. }
  372. }
  373. private SearchWsResponse doHandle(SearchRequest request) {
  374. // prepare the Elasticsearch request
  375. SearchOptions options = createSearchOptionsFromRequest(request);
  376. EnumSet<SearchAdditionalField> additionalFields = SearchAdditionalField.getFromRequest(request);
  377. IssueQuery query = issueQueryFactory.create(request);
  378. Set<String> facetsRequiringProjectParameter = options.getFacets().stream()
  379. .filter(FACETS_REQUIRING_PROJECT::contains)
  380. .collect(toSet());
  381. checkArgument(facetsRequiringProjectParameter.isEmpty() ||
  382. (!query.projectUuids().isEmpty()), "Facet(s) '%s' require to also filter by project",
  383. String.join(",", facetsRequiringProjectParameter));
  384. // execute request
  385. SearchResponse result = issueIndex.search(query, options);
  386. List<String> issueKeys = Arrays.stream(result.getHits().getHits())
  387. .map(SearchHit::getId)
  388. .collect(MoreCollectors.toList(result.getHits().getHits().length));
  389. // load the additional information to be returned in response
  390. SearchResponseLoader.Collector collector = new SearchResponseLoader.Collector(issueKeys);
  391. collectLoggedInUser(collector);
  392. collectRequestParams(collector, request);
  393. Facets facets = new Facets(result, Optional.ofNullable(query.timeZone()).orElse(system2.getDefaultTimeZone().toZoneId()));
  394. if (!options.getFacets().isEmpty()) {
  395. // add missing values to facets. For example if assignee "john" and facet on "assignees" are requested, then
  396. // "john" should always be listed in the facet. If it is not present, then it is added with value zero.
  397. // This is a constraint from webapp UX.
  398. completeFacets(facets, request, query);
  399. collectFacets(collector, facets);
  400. }
  401. SearchResponseData preloadedData = new SearchResponseData(emptyList());
  402. preloadedData.addRules(ImmutableList.copyOf(query.rules()));
  403. SearchResponseData data = searchResponseLoader.load(preloadedData, collector, additionalFields, facets);
  404. // FIXME allow long in Paging
  405. Paging paging = forPageIndex(options.getPage()).withPageSize(options.getLimit()).andTotal((int) result.getHits().getTotalHits().value);
  406. return searchResponseFormat.formatSearch(additionalFields, data, paging, facets);
  407. }
  408. private static SearchOptions createSearchOptionsFromRequest(SearchRequest request) {
  409. SearchOptions options = new SearchOptions();
  410. options.setPage(request.getPage(), request.getPageSize());
  411. List<String> facets = request.getFacets();
  412. if (facets == null || facets.isEmpty()) {
  413. return options;
  414. }
  415. options.addFacets(facets);
  416. return options;
  417. }
  418. private void completeFacets(Facets facets, SearchRequest request, IssueQuery query) {
  419. addMandatoryValuesToFacet(facets, PARAM_SEVERITIES, Severity.ALL);
  420. addMandatoryValuesToFacet(facets, PARAM_STATUSES, ISSUE_STATUSES);
  421. addMandatoryValuesToFacet(facets, PARAM_RESOLUTIONS, concat(singletonList(""), RESOLUTIONS));
  422. addMandatoryValuesToFacet(facets, FACET_PROJECTS, query.projectUuids());
  423. addMandatoryValuesToFacet(facets, PARAM_MODULE_UUIDS, query.moduleUuids());
  424. addMandatoryValuesToFacet(facets, PARAM_FILES, query.files());
  425. List<String> assignees = Lists.newArrayList("");
  426. List<String> assigneesFromRequest = request.getAssigneeUuids();
  427. if (assigneesFromRequest != null) {
  428. assignees.addAll(assigneesFromRequest);
  429. assignees.remove(LOGIN_MYSELF);
  430. }
  431. addMandatoryValuesToFacet(facets, PARAM_ASSIGNEES, assignees);
  432. addMandatoryValuesToFacet(facets, FACET_ASSIGNED_TO_ME, singletonList(userSession.getUuid()));
  433. addMandatoryValuesToFacet(facets, PARAM_RULES, query.ruleUuids());
  434. addMandatoryValuesToFacet(facets, PARAM_SCOPES, ISSUE_SCOPES);
  435. addMandatoryValuesToFacet(facets, PARAM_LANGUAGES, request.getLanguages());
  436. addMandatoryValuesToFacet(facets, PARAM_TAGS, request.getTags());
  437. setTypesFacet(facets);
  438. addMandatoryValuesToFacet(facets, PARAM_OWASP_TOP_10, request.getOwaspTop10());
  439. addMandatoryValuesToFacet(facets, PARAM_SANS_TOP_25, request.getSansTop25());
  440. addMandatoryValuesToFacet(facets, PARAM_CWE, request.getCwe());
  441. addMandatoryValuesToFacet(facets, PARAM_SONARSOURCE_SECURITY, request.getSonarsourceSecurity());
  442. }
  443. private static void setTypesFacet(Facets facets) {
  444. Map<String, Long> typeFacet = facets.get(PARAM_TYPES);
  445. if (typeFacet != null) {
  446. typeFacet.remove(RuleType.SECURITY_HOTSPOT.name());
  447. }
  448. addMandatoryValuesToFacet(facets, PARAM_TYPES, ALL_RULE_TYPES_EXCEPT_SECURITY_HOTSPOTS.stream().map(Enum::name).collect(Collectors.toList()));
  449. }
  450. private static void addMandatoryValuesToFacet(Facets facets, String facetName, @Nullable Iterable<String> mandatoryValues) {
  451. Map<String, Long> buckets = facets.get(facetName);
  452. if (buckets != null && mandatoryValues != null) {
  453. for (String mandatoryValue : mandatoryValues) {
  454. if (!buckets.containsKey(mandatoryValue)) {
  455. buckets.put(mandatoryValue, 0L);
  456. }
  457. }
  458. }
  459. }
  460. private void collectLoggedInUser(SearchResponseLoader.Collector collector) {
  461. if (userSession.isLoggedIn()) {
  462. collector.addUserUuids(singletonList(userSession.getUuid()));
  463. }
  464. }
  465. private static void collectFacets(SearchResponseLoader.Collector collector, Facets facets) {
  466. collector.addProjectUuids(facets.getBucketKeys(FACET_PROJECTS));
  467. collector.addComponentUuids(facets.getBucketKeys(PARAM_MODULE_UUIDS));
  468. collector.addRuleIds(facets.getBucketKeys(PARAM_RULES));
  469. collector.addUserUuids(facets.getBucketKeys(PARAM_ASSIGNEES));
  470. }
  471. private static void collectRequestParams(SearchResponseLoader.Collector collector, SearchRequest request) {
  472. collector.addComponentUuids(request.getModuleUuids());
  473. collector.addUserUuids(request.getAssigneeUuids());
  474. }
  475. private SearchRequest toSearchWsRequest(DbSession dbSession, Request request) {
  476. return new SearchRequest()
  477. .setAdditionalFields(request.paramAsStrings(PARAM_ADDITIONAL_FIELDS))
  478. .setAsc(request.mandatoryParamAsBoolean(PARAM_ASC))
  479. .setAssigned(request.paramAsBoolean(PARAM_ASSIGNED))
  480. .setAssigneesUuid(getLogins(dbSession, request.paramAsStrings(PARAM_ASSIGNEES)))
  481. .setAuthors(request.hasParam(PARAM_AUTHOR) ? request.multiParam(PARAM_AUTHOR) : request.paramAsStrings(DEPRECATED_PARAM_AUTHORS))
  482. .setComponents(request.paramAsStrings(PARAM_COMPONENT_KEYS))
  483. .setCreatedAfter(request.param(PARAM_CREATED_AFTER))
  484. .setCreatedAt(request.param(PARAM_CREATED_AT))
  485. .setCreatedBefore(request.param(PARAM_CREATED_BEFORE))
  486. .setCreatedInLast(request.param(PARAM_CREATED_IN_LAST))
  487. .setDirectories(request.paramAsStrings(PARAM_DIRECTORIES))
  488. .setFacetMode(request.mandatoryParam(FACET_MODE))
  489. .setFacets(request.paramAsStrings(FACETS))
  490. .setFiles(request.paramAsStrings(PARAM_FILES))
  491. .setIssues(request.paramAsStrings(PARAM_ISSUES))
  492. .setScopes(request.paramAsStrings(PARAM_SCOPES))
  493. .setLanguages(request.paramAsStrings(PARAM_LANGUAGES))
  494. .setModuleUuids(request.paramAsStrings(PARAM_MODULE_UUIDS))
  495. .setOnComponentOnly(request.paramAsBoolean(PARAM_ON_COMPONENT_ONLY))
  496. .setBranch(request.param(PARAM_BRANCH))
  497. .setPullRequest(request.param(PARAM_PULL_REQUEST))
  498. .setPage(request.mandatoryParamAsInt(Param.PAGE))
  499. .setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE))
  500. .setProjects(request.paramAsStrings(PARAM_PROJECTS))
  501. .setResolutions(request.paramAsStrings(PARAM_RESOLUTIONS))
  502. .setResolved(request.paramAsBoolean(PARAM_RESOLVED))
  503. .setRules(request.paramAsStrings(PARAM_RULES))
  504. .setSinceLeakPeriod(request.mandatoryParamAsBoolean(PARAM_SINCE_LEAK_PERIOD))
  505. .setSort(request.param(Param.SORT))
  506. .setSeverities(request.paramAsStrings(PARAM_SEVERITIES))
  507. .setStatuses(request.paramAsStrings(PARAM_STATUSES))
  508. .setTags(request.paramAsStrings(PARAM_TAGS))
  509. .setTypes(allRuleTypesExceptHotspotsIfEmpty(request.paramAsStrings(PARAM_TYPES)))
  510. .setOwaspTop10(request.paramAsStrings(PARAM_OWASP_TOP_10))
  511. .setSansTop25(request.paramAsStrings(PARAM_SANS_TOP_25))
  512. .setCwe(request.paramAsStrings(PARAM_CWE))
  513. .setSonarsourceSecurity(request.paramAsStrings(PARAM_SONARSOURCE_SECURITY))
  514. .setTimeZone(request.param(PARAM_TIMEZONE));
  515. }
  516. private void checkIfNeedIssueSync(DbSession dbSession, SearchRequest searchRequest) {
  517. List<String> components = searchRequest.getComponents();
  518. if (components != null && !components.isEmpty()) {
  519. issueIndexSyncProgressChecker.checkIfAnyComponentsNeedIssueSync(dbSession, components);
  520. } else {
  521. // component keys not provided - asking for global
  522. issueIndexSyncProgressChecker.checkIfIssueSyncInProgress(dbSession);
  523. }
  524. }
  525. private static List<String> allRuleTypesExceptHotspotsIfEmpty(@Nullable List<String> types) {
  526. if (types == null || types.isEmpty()) {
  527. return ALL_RULE_TYPES_EXCEPT_SECURITY_HOTSPOTS.stream().map(Enum::name).collect(toList());
  528. }
  529. return types;
  530. }
  531. private List<String> getLogins(DbSession dbSession, @Nullable List<String> assigneeLogins) {
  532. List<String> userLogins = new ArrayList<>();
  533. for (String login : ofNullable(assigneeLogins).orElse(emptyList())) {
  534. if (LOGIN_MYSELF.equals(login)) {
  535. if (userSession.getLogin() == null) {
  536. userLogins.add(UNKNOWN);
  537. } else {
  538. userLogins.add(userSession.getLogin());
  539. }
  540. } else {
  541. userLogins.add(login);
  542. }
  543. }
  544. List<UserDto> userDtos = dbClient.userDao().selectByLogins(dbSession, userLogins);
  545. List<String> assigneeUuid = userDtos.stream().map(UserDto::getUuid).collect(toList());
  546. if ((assigneeLogins != null) && firstNonNull(assigneeUuid, emptyList()).isEmpty()) {
  547. assigneeUuid = ImmutableList.of("non-existent-uuid");
  548. }
  549. return assigneeUuid;
  550. }
  551. }