aboutsummaryrefslogtreecommitdiffstats
path: root/sonar-scanner-engine/src/test/java/org/sonar/scanner/sca/CliCacheServiceTest.java
blob: 6615ba4e4e4d5c0a56516c2acd77c0418955f1bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/*
 * SonarQube
 * Copyright (C) 2009-2025 SonarSource SA
 * mailto:info AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package org.sonar.scanner.sca;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.SystemUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTesterJUnit5;
import org.sonar.api.utils.System2;
import org.sonar.scanner.WsTestUtil;
import org.sonar.scanner.bootstrap.SonarUserHome;
import org.sonar.scanner.http.DefaultScannerWsClient;
import org.sonar.scanner.repository.TelemetryCache;
import org.sonarqube.ws.client.HttpException;
import org.sonarqube.ws.client.WsResponse;

import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sonar.scanner.sca.CliCacheService.CLI_WS_URL;

@ExtendWith(MockitoExtension.class)
class CliCacheServiceTest {
  @Mock
  private SonarUserHome sonarUserHome;
  @Mock
  private DefaultScannerWsClient scannerWsClient;
  @Mock
  private System2 system2;
  @Mock
  private TelemetryCache telemetryCache;
  @RegisterExtension
  private final LogTesterJUnit5 logTester = new LogTesterJUnit5();
  @TempDir
  public Path cacheDir;

  private CliCacheService underTest;

  @BeforeEach
  void setup() {
    lenient().when(sonarUserHome.getPath()).thenReturn(cacheDir);
    lenient().when(telemetryCache.put(any(), any())).thenReturn(telemetryCache);

    underTest = new CliCacheService(sonarUserHome, scannerWsClient, telemetryCache, system2);
  }

  @Test
  void cacheCli_shouldDownloadCli_whenCacheDoesNotExist() {
    String checksum = "checksum";
    String id = "tidelift";
    WsTestUtil.mockReader(scannerWsClient, CLI_WS_URL, new StringReader("""
      [
        {
          "id": "%s",
          "filename": "tidelift_darwin",
          "sha256": "%s",
          "os": "mac",
          "arch": "x64_86"
        }
      ]""".formatted(id, checksum)));

    WsTestUtil.mockStream(scannerWsClient, CLI_WS_URL + "/" + id, new ByteArrayInputStream("cli content".getBytes()));

    assertThat(cacheDir).isEmptyDirectory();

    File generatedFile = underTest.cacheCli();

    assertThat(generatedFile).exists().isExecutable();
    assertThat(cacheDir.resolve("cache").resolve(checksum)).exists().isNotEmptyDirectory();

    verify(telemetryCache).put(eq("scanner.sca.download.cli.duration"), any());
    verify(telemetryCache).put("scanner.sca.download.cli.success", "true");
    verify(telemetryCache).put("scanner.sca.get.cli.cache.hit", "false");
    verify(telemetryCache).put("scanner.sca.get.cli.success", "true");
  }

  @Test
  void cacheCli_shouldThrowException_whenMultipleMetadatas() {
    WsTestUtil.mockReader(scannerWsClient, CLI_WS_URL, new StringReader("""
      [
        {
          "id": "tidelift",
          "filename": "tidelift_darwin",
          "sha256": "1",
          "os": "mac",
          "arch": "x64_86"
        },
        {
          "id": "tidelift_other",
          "filename": "tidelift",
          "sha256": "2",
          "os": "mac",
          "arch": "x64_86"
        }
      ]"""));

    assertThatThrownBy(underTest::cacheCli).isInstanceOf(IllegalStateException.class)
      .hasMessageContaining("Multiple CLI matches found. Unable to correctly cache CLI.");

    verify(telemetryCache).put("scanner.sca.get.cli.success", "false");

  }

  @Test
  void cacheCli_shouldThrowException_whenNoMetadata() {
    WsTestUtil.mockReader(scannerWsClient, CLI_WS_URL, new StringReader("[]"));

    assertThatThrownBy(underTest::cacheCli).isInstanceOf(IllegalStateException.class)
      .hasMessageMatching("Could not find CLI for .+ .+");

    verify(telemetryCache).put("scanner.sca.get.cli.success", "false");

  }

  @Test
  void cacheCli_shouldThrowException_whenServerError() {
    HttpException http = new HttpException("url", 500, "some error message");
    IllegalStateException e = new IllegalStateException("http error", http);
    WsTestUtil.mockException(scannerWsClient, e);

    assertThatThrownBy(underTest::cacheCli).isInstanceOf(IllegalStateException.class)
      .hasMessageContaining("http error");

    verify(telemetryCache).put("scanner.sca.get.cli.success", "false");
  }

  @Test
  void cacheCli_shouldNotOverwrite_whenCachedFileExists() throws IOException {
    String checksum = "checksum";
    WsTestUtil.mockReader(scannerWsClient, CLI_WS_URL, new StringReader("""
      [
        {
          "id": "tidelift",
          "filename": "tidelift_darwin",
          "sha256": "%s",
          "os": "mac",
          "arch": "x64_86"
        }
      ]""".formatted(checksum)));
    when(system2.isOsWindows()).thenReturn(false);

    String fileContent = "test content";
    File existingFile = underTest.cacheDir().resolve(checksum).resolve("tidelift").toFile();
    FileUtils.createParentDirectories(existingFile);
    FileUtils.writeStringToFile(existingFile, fileContent, Charset.defaultCharset());

    assertThat(existingFile).exists();
    if (!SystemUtils.IS_OS_WINDOWS) {
      assertThat(existingFile.canExecute()).isFalse();
    }
    assertThat(FileUtils.readFileToString(existingFile, Charset.defaultCharset())).isEqualTo(fileContent);

    underTest.cacheCli();

    WsTestUtil.verifyCall(scannerWsClient, CLI_WS_URL);
    assertThat(existingFile).exists();
    if (!SystemUtils.IS_OS_WINDOWS) {
      assertThat(existingFile.canExecute()).isFalse();
    }
    assertThat(FileUtils.readFileToString(existingFile, Charset.defaultCharset())).isEqualTo(fileContent);

    verify(telemetryCache).put("scanner.sca.get.cli.cache.hit", "true");
    verify(telemetryCache).put("scanner.sca.get.cli.success", "true");
  }

  @Test
  void cacheCli_shouldAllowLocationOverride(@TempDir Path tempDir) throws IOException {
    File alternateCliFile = tempDir.resolve("alternate_cli").toFile();
    FileUtils.writeStringToFile(alternateCliFile, "alternate cli content", Charset.defaultCharset());
    when(system2.envVariable("TIDELIFT_CLI_LOCATION")).thenReturn(alternateCliFile.getAbsolutePath());

    var returnedFile = underTest.cacheCli();

    assertThat(returnedFile.getAbsolutePath()).isEqualTo(alternateCliFile.getAbsolutePath());
    assertThat(logTester.logs(Level.INFO)).contains("Using alternate location for Tidelift CLI: " + alternateCliFile.getAbsolutePath());
    verify(scannerWsClient, never()).call(any());
  }

  @Test
  void cacheCli_whenOverrideDoesntExist_shouldRaiseError() {
    var location = "incorrect_location";
    when(system2.envVariable("TIDELIFT_CLI_LOCATION")).thenReturn(location);

    assertThatThrownBy(underTest::cacheCli).isInstanceOf(IllegalStateException.class)
      .hasMessageMatching("Alternate location for Tidelift CLI has been set but no file was found at " + location);

    assertThat(logTester.logs(Level.INFO)).contains("Using alternate location for Tidelift CLI: " + location);
    verify(scannerWsClient, never()).call(any());
  }

  @Test
  void apiOsName_shouldReturnApiCompatibleName() {
    when(system2.isOsWindows()).thenReturn(true);
    when(system2.isOsMac()).thenReturn(false);
    assertThat(underTest.apiOsName()).isEqualTo("windows");
    reset(system2);

    when(system2.isOsWindows()).thenReturn(false);
    when(system2.isOsMac()).thenReturn(true);
    assertThat(underTest.apiOsName()).isEqualTo("mac");

    reset(system2);
    when(system2.isOsWindows()).thenReturn(false);
    when(system2.isOsMac()).thenReturn(false);
    assertThat(underTest.apiOsName()).isEqualTo("linux");
  }

  @Test
  void createTempDir_shouldReturnExistingDir() throws IOException {
    Path dir = sonarUserHome.getPath().resolve("_tmp");
    Files.createDirectory(dir);

    assertThat(underTest.createTempDir()).isEqualTo(dir);
  }

  @Test
  void createTempDir_shouldHandleIOException() {
    try (MockedStatic<Files> mockFilesClass = mockStatic(Files.class)) {
      mockFilesClass.when(() -> Files.createDirectory(any(Path.class))).thenThrow(IOException.class);

      Path expectedDir = sonarUserHome.getPath().resolve("_tmp");
      assertThatThrownBy(underTest::createTempDir).isInstanceOf(IllegalStateException.class)
        .hasMessageContaining(format("Unable to create temp directory at %s", expectedDir));
    }
  }

  @Test
  void moveFile_shouldHandleIOException(@TempDir Path sourceFile, @TempDir Path targetFile) {
    try (MockedStatic<Files> mockFilesClass = mockStatic(Files.class)) {
      mockFilesClass.when(() -> Files.move(sourceFile, targetFile, StandardCopyOption.ATOMIC_MOVE)).thenThrow(IOException.class);
      mockFilesClass.when(() -> Files.move(sourceFile, targetFile)).thenThrow(IOException.class);

      assertThatThrownBy(() -> CliCacheService.moveFile(sourceFile, targetFile)).isInstanceOf(IllegalStateException.class)
        .hasMessageContaining(format("Fail to move %s to %s", sourceFile, targetFile));

      assertThat(logTester.logs(Level.WARN)).contains(format("Unable to rename %s to %s", sourceFile, targetFile));
      assertThat(logTester.logs(Level.WARN)).contains("A copy/delete will be tempted but with no guarantee of atomicity");
    }
  }

  @Test
  void mkdir_shouldHandleIOException(@TempDir Path dir) {
    try (MockedStatic<Files> mockFilesClass = mockStatic(Files.class)) {
      mockFilesClass.when(() -> Files.createDirectories(dir)).thenThrow(IOException.class);

      assertThatThrownBy(() -> CliCacheService.mkdir(dir)).isInstanceOf(IllegalStateException.class)
        .hasMessageContaining(format("Fail to create cache directory: %s", dir));
    }
  }

  @Test
  void downloadBinaryTo_shouldHandleIOException(@TempDir Path downloadLocation) {
    WsResponse mockResponse = mock(WsResponse.class);
    InputStream mockStream = mock(InputStream.class);
    when(mockResponse.contentStream()).thenReturn(mockStream);

    try (MockedStatic<FileUtils> mockFileUtils = mockStatic(FileUtils.class)) {
      mockFileUtils.when(() -> FileUtils.copyInputStreamToFile(mockStream, downloadLocation.toFile())).thenThrow(IOException.class);

      assertThatThrownBy(() -> CliCacheService.downloadBinaryTo(downloadLocation, mockResponse)).isInstanceOf(IllegalStateException.class)
        .hasMessageContaining(format("Fail to download SCA CLI into %s", downloadLocation));
    }
  }
}