Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

SarifIssuesImportSensorTest.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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.scanner.externalissue.sarif;
  21. import com.google.common.collect.MoreCollectors;
  22. import java.nio.file.NoSuchFileException;
  23. import java.nio.file.Path;
  24. import java.util.Optional;
  25. import org.junit.Before;
  26. import org.junit.Rule;
  27. import org.junit.Test;
  28. import org.junit.runner.RunWith;
  29. import org.mockito.Mock;
  30. import org.mockito.junit.MockitoJUnitRunner;
  31. import org.slf4j.event.Level;
  32. import org.sonar.api.batch.sensor.internal.SensorContextTester;
  33. import org.sonar.api.config.internal.MapSettings;
  34. import org.sonar.api.testfixtures.log.LogAndArguments;
  35. import org.sonar.api.testfixtures.log.LogTester;
  36. import org.sonar.api.utils.MessageException;
  37. import org.sonar.api.utils.log.LoggerLevel;
  38. import org.sonar.core.sarif.Sarif210;
  39. import org.sonar.core.sarif.SarifSerializer;
  40. import static org.assertj.core.api.Assertions.assertThat;
  41. import static org.assertj.core.api.Assertions.assertThatThrownBy;
  42. import static org.mockito.Mockito.doThrow;
  43. import static org.mockito.Mockito.mock;
  44. import static org.mockito.Mockito.verify;
  45. import static org.mockito.Mockito.when;
  46. @RunWith(MockitoJUnitRunner.class)
  47. public class SarifIssuesImportSensorTest {
  48. private static final String FILE_1 = "path/to/sarif/file.sarif";
  49. private static final String FILE_2 = "path/to/sarif/file2.sarif";
  50. private static final String SARIF_REPORT_PATHS_PARAM = FILE_1 + "," + FILE_2;
  51. @Mock
  52. private SarifSerializer sarifSerializer;
  53. @Mock
  54. private Sarif210Importer sarifImporter;
  55. private MapSettings sensorSettings;
  56. @Before
  57. public void before() {
  58. sensorSettings = new MapSettings();
  59. }
  60. @Rule
  61. public final LogTester logTester = new LogTester();
  62. private final SensorContextTester sensorContext = SensorContextTester.create(Path.of("."));
  63. @Test
  64. public void execute_whenSingleFileIsSpecified_shouldImportResults() throws NoSuchFileException {
  65. sensorSettings.setProperty("sonar.sarifReportPaths", FILE_1);
  66. ReportAndResults reportAndResults = mockSuccessfulReportAndResults(FILE_1);
  67. SarifIssuesImportSensor sensor = new SarifIssuesImportSensor(sarifSerializer, sarifImporter, sensorSettings.asConfig());
  68. sensor.execute(sensorContext);
  69. verify(sarifImporter).importSarif(reportAndResults.getSarifReport());
  70. assertThat(logTester.logs(Level.INFO)).hasSize(1);
  71. assertSummaryIsCorrectlyDisplayedForSuccessfulFile(FILE_1, reportAndResults.getSarifImportResults());
  72. }
  73. @Test
  74. public void execute_whenMultipleFilesAreSpecified_shouldImportResults() throws NoSuchFileException {
  75. sensorSettings.setProperty("sonar.sarifReportPaths", SARIF_REPORT_PATHS_PARAM);
  76. ReportAndResults reportAndResults1 = mockSuccessfulReportAndResults(FILE_1);
  77. ReportAndResults reportAndResults2 = mockSuccessfulReportAndResults(FILE_2);
  78. SarifIssuesImportSensor sensor = new SarifIssuesImportSensor(sarifSerializer, sarifImporter, sensorSettings.asConfig());
  79. sensor.execute(sensorContext);
  80. verify(sarifImporter).importSarif(reportAndResults1.getSarifReport());
  81. verify(sarifImporter).importSarif(reportAndResults2.getSarifReport());
  82. assertSummaryIsCorrectlyDisplayedForSuccessfulFile(FILE_1, reportAndResults1.getSarifImportResults());
  83. assertSummaryIsCorrectlyDisplayedForSuccessfulFile(FILE_2, reportAndResults2.getSarifImportResults());
  84. }
  85. @Test
  86. public void execute_whenFileContainsOnlySuccessfulRuns_shouldLogCorrectMessage() throws NoSuchFileException {
  87. sensorSettings.setProperty("sonar.sarifReportPaths", FILE_1);
  88. ReportAndResults reportAndResults = mockSuccessfulReportAndResults(FILE_1);
  89. SarifIssuesImportSensor sensor = new SarifIssuesImportSensor(sarifSerializer, sarifImporter, sensorSettings.asConfig());
  90. sensor.execute(sensorContext);
  91. assertSummaryIsCorrectlyDisplayedForSuccessfulFile(FILE_1, reportAndResults.getSarifImportResults());
  92. }
  93. @Test
  94. public void execute_whenFileContainsOnlyFailedRuns_shouldLogCorrectMessage() throws NoSuchFileException {
  95. sensorSettings.setProperty("sonar.sarifReportPaths", FILE_1);
  96. ReportAndResults reportAndResults = mockFailedReportAndResults(FILE_1);
  97. SarifIssuesImportSensor sensor = new SarifIssuesImportSensor(sarifSerializer, sarifImporter, sensorSettings.asConfig());
  98. sensor.execute(sensorContext);
  99. assertSummaryIsCorrectlyDisplayedForFailedFile(FILE_1, reportAndResults.getSarifImportResults());
  100. }
  101. @Test
  102. public void execute_whenFileContainsFailedAndSuccessfulRuns_shouldLogCorrectMessage() throws NoSuchFileException {
  103. sensorSettings.setProperty("sonar.sarifReportPaths", FILE_1);
  104. ReportAndResults reportAndResults = mockMixedReportAndResults(FILE_1);
  105. SarifIssuesImportSensor sensor = new SarifIssuesImportSensor(sarifSerializer, sarifImporter, sensorSettings.asConfig());
  106. sensor.execute(sensorContext);
  107. verify(sarifImporter).importSarif(reportAndResults.getSarifReport());
  108. assertSummaryIsCorrectlyDisplayedForMixedFile(FILE_1, reportAndResults.getSarifImportResults());
  109. }
  110. @Test
  111. public void execute_whenImportFails_shouldSkipReport() throws NoSuchFileException {
  112. sensorSettings.setProperty("sonar.sarifReportPaths", SARIF_REPORT_PATHS_PARAM);
  113. ReportAndResults reportAndResults1 = mockFailedReportAndResults(FILE_1);
  114. ReportAndResults reportAndResults2 = mockSuccessfulReportAndResults(FILE_2);
  115. doThrow(new NullPointerException("import failed")).when(sarifImporter).importSarif(reportAndResults1.getSarifReport());
  116. SarifIssuesImportSensor sensor = new SarifIssuesImportSensor(sarifSerializer, sarifImporter, sensorSettings.asConfig());
  117. sensor.execute(sensorContext);
  118. verify(sarifImporter).importSarif(reportAndResults2.getSarifReport());
  119. assertThat(logTester.logs(Level.WARN)).contains("Failed to process SARIF report from file 'path/to/sarif/file.sarif', error: 'import failed'");
  120. assertSummaryIsCorrectlyDisplayedForSuccessfulFile(FILE_2, reportAndResults2.getSarifImportResults());
  121. }
  122. @Test
  123. public void execute_whenDeserializationFails_shouldSkipReport() throws NoSuchFileException {
  124. sensorSettings.setProperty("sonar.sarifReportPaths", SARIF_REPORT_PATHS_PARAM);
  125. failDeserializingReport(FILE_1);
  126. ReportAndResults reportAndResults2 = mockSuccessfulReportAndResults(FILE_2);
  127. SarifIssuesImportSensor sensor = new SarifIssuesImportSensor(sarifSerializer, sarifImporter, sensorSettings.asConfig());
  128. sensor.execute(sensorContext);
  129. verify(sarifImporter).importSarif(reportAndResults2.getSarifReport());
  130. assertThat(logTester.logs(Level.WARN)).contains("Failed to process SARIF report from file 'path/to/sarif/file.sarif', error: 'deserialization failed'");
  131. assertSummaryIsCorrectlyDisplayedForSuccessfulFile(FILE_2, reportAndResults2.getSarifImportResults());
  132. }
  133. @Test
  134. public void execute_whenDeserializationThrowsMessageException_shouldRethrow() throws NoSuchFileException {
  135. sensorSettings.setProperty("sonar.sarifReportPaths", FILE_1);
  136. NoSuchFileException e = new NoSuchFileException("non-existent");
  137. failDeserializingReportWithException(FILE_1, e);
  138. SarifIssuesImportSensor sensor = new SarifIssuesImportSensor(sarifSerializer, sarifImporter, sensorSettings.asConfig());
  139. assertThatThrownBy(() -> sensor.execute(sensorContext))
  140. .isInstanceOf(MessageException.class)
  141. .hasMessage("SARIF report file not found: non-existent");
  142. }
  143. private void failDeserializingReport(String path) throws NoSuchFileException {
  144. Path reportFilePath = sensorContext.fileSystem().resolvePath(path).toPath();
  145. when(sarifSerializer.deserialize(reportFilePath)).thenThrow(new NullPointerException("deserialization failed"));
  146. }
  147. private void failDeserializingReportWithException(String path, Exception exception) throws NoSuchFileException {
  148. Path reportFilePath = sensorContext.fileSystem().resolvePath(path).toPath();
  149. when(sarifSerializer.deserialize(reportFilePath)).thenThrow(exception);
  150. }
  151. private ReportAndResults mockSuccessfulReportAndResults(String path) throws NoSuchFileException {
  152. Sarif210 report = mockSarifReport(path);
  153. SarifImportResults sarifImportResults = mock(SarifImportResults.class);
  154. when(sarifImportResults.getSuccessFullyImportedIssues()).thenReturn(10);
  155. when(sarifImportResults.getSuccessFullyImportedRuns()).thenReturn(3);
  156. when(sarifImportResults.getFailedRuns()).thenReturn(0);
  157. when(sarifImporter.importSarif(report)).thenReturn(sarifImportResults);
  158. return new ReportAndResults(report, sarifImportResults);
  159. }
  160. private Sarif210 mockSarifReport(String path) throws NoSuchFileException {
  161. Sarif210 report = mock(Sarif210.class);
  162. Path reportFilePath = sensorContext.fileSystem().resolvePath(path).toPath();
  163. when(sarifSerializer.deserialize(reportFilePath)).thenReturn(report);
  164. return report;
  165. }
  166. private ReportAndResults mockFailedReportAndResults(String path) throws NoSuchFileException {
  167. Sarif210 report = mockSarifReport(path);
  168. SarifImportResults sarifImportResults = mock(SarifImportResults.class);
  169. when(sarifImportResults.getSuccessFullyImportedRuns()).thenReturn(0);
  170. when(sarifImportResults.getFailedRuns()).thenReturn(1);
  171. when(sarifImporter.importSarif(report)).thenReturn(sarifImportResults);
  172. return new ReportAndResults(report, sarifImportResults);
  173. }
  174. private ReportAndResults mockMixedReportAndResults(String path) throws NoSuchFileException {
  175. Sarif210 report = mockSarifReport(path);
  176. SarifImportResults sarifImportResults = mock(SarifImportResults.class);
  177. when(sarifImportResults.getSuccessFullyImportedIssues()).thenReturn(10);
  178. when(sarifImportResults.getSuccessFullyImportedRuns()).thenReturn(3);
  179. when(sarifImportResults.getFailedRuns()).thenReturn(1);
  180. when(sarifImporter.importSarif(report)).thenReturn(sarifImportResults);
  181. return new ReportAndResults(report, sarifImportResults);
  182. }
  183. private void assertSummaryIsCorrectlyDisplayedForSuccessfulFile(String filePath, SarifImportResults sarifImportResults) {
  184. verifyLogContainsLine(LoggerLevel.INFO, filePath, "File {}: {} run(s) successfully imported ({} vulnerabilities in total).",
  185. filePath, sarifImportResults.getSuccessFullyImportedRuns(), sarifImportResults.getSuccessFullyImportedIssues());
  186. }
  187. private void assertSummaryIsCorrectlyDisplayedForFailedFile(String filePath, SarifImportResults sarifImportResults) {
  188. verifyLogContainsLine(LoggerLevel.WARN, filePath, "File {}: {} run(s) could not be imported (see warning above).",
  189. filePath, sarifImportResults.getFailedRuns());
  190. }
  191. private void assertSummaryIsCorrectlyDisplayedForMixedFile(String filePath, SarifImportResults sarifImportResults) {
  192. verifyLogContainsLine(LoggerLevel.WARN, filePath,
  193. "File {}: {} run(s) could not be imported (see warning above) and {} run(s) successfully imported ({} vulnerabilities in total).",
  194. filePath, sarifImportResults.getFailedRuns(), sarifImportResults.getSuccessFullyImportedRuns(), sarifImportResults.getSuccessFullyImportedIssues());
  195. }
  196. private void verifyLogContainsLine(LoggerLevel level, String filePath, String rawMsg, Object... arguments) {
  197. LogAndArguments logAndArguments = findLogEntry(level, filePath);
  198. assertThat(logAndArguments.getRawMsg())
  199. .isEqualTo(rawMsg);
  200. assertThat(logAndArguments.getArgs()).isPresent()
  201. .contains(arguments);
  202. }
  203. private LogAndArguments findLogEntry(LoggerLevel level, String filePath) {
  204. Optional<LogAndArguments> optLogAndArguments = logTester.getLogs(level).stream()
  205. .filter(log -> log.getFormattedMsg().contains(filePath))
  206. .collect(MoreCollectors.toOptional());
  207. assertThat(optLogAndArguments).as("Log entry missing for file %s", filePath).isPresent();
  208. return optLogAndArguments.get();
  209. }
  210. private static class ReportAndResults {
  211. private final Sarif210 sarifReport;
  212. private final SarifImportResults sarifImportResults;
  213. private ReportAndResults(Sarif210 sarifReport, SarifImportResults sarifImportResults) {
  214. this.sarifReport = sarifReport;
  215. this.sarifImportResults = sarifImportResults;
  216. }
  217. private Sarif210 getSarifReport() {
  218. return sarifReport;
  219. }
  220. private SarifImportResults getSarifImportResults() {
  221. return sarifImportResults;
  222. }
  223. }
  224. }