forked from guacsec/trustify-da-java-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExhortApiIT.java
More file actions
395 lines (363 loc) · 16.5 KB
/
Copy pathExhortApiIT.java
File metadata and controls
395 lines (363 loc) · 16.5 KB
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
/*
* Copyright 2023-2025 Trustify Dependency Analytics Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.guacsec.trustifyda.impl;
import static io.github.guacsec.trustifyda.Provider.PROP_MATCH_MANIFEST_VERSIONS;
import static io.github.guacsec.trustifyda.image.ImageUtils.SKIP_VALIDATION_KEY;
import static io.github.guacsec.trustifyda.utils.PythonControllerBase.PROP_TRUSTIFY_DA_PYTHON_INSTALL_BEST_EFFORTS;
import static io.github.guacsec.trustifyda.utils.PythonControllerBase.PROP_TRUSTIFY_DA_PYTHON_VIRTUAL_ENV;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.AdditionalMatchers.aryEq;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mockStatic;
import io.github.guacsec.trustifyda.Api;
import io.github.guacsec.trustifyda.ExhortTest;
import io.github.guacsec.trustifyda.api.v5.AnalysisReport;
import io.github.guacsec.trustifyda.api.v5.ProviderReport;
import io.github.guacsec.trustifyda.image.ImageRef;
import io.github.guacsec.trustifyda.providers.HelperExtension;
import io.github.guacsec.trustifyda.providers.JavaScriptNpmProvider;
import io.github.guacsec.trustifyda.providers.JavaScriptPnpmProvider;
import io.github.guacsec.trustifyda.providers.JavaScriptYarnProvider;
import io.github.guacsec.trustifyda.tools.Ecosystem;
import io.github.guacsec.trustifyda.tools.Operations;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.AbstractMap;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junitpioneer.jupiter.RestoreSystemProperties;
import org.junitpioneer.jupiter.SetSystemProperty;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.jupiter.MockitoExtension;
@Tag("IntegrationTest")
@ExtendWith(HelperExtension.class)
@ExtendWith(MockitoExtension.class)
@SetSystemProperty(key = "TRUSTIFY_DA_BACKEND_URL", value = "https://exhort.stage.devshift.net")
@SetSystemProperty(key = "TRUST_DA_SOURCE", value = "trustify-da-java-client-it")
@RestoreSystemProperties
class ExhortApiIT extends ExhortTest {
private static Api api;
private static Map<String, AbstractMap.SimpleEntry<String, Optional<String>>>
ecoSystemsManifestNames;
private MockedStatic<Operations> mockedOperations;
@BeforeAll
static void beforeAll() {
api = new ExhortApi();
ecoSystemsManifestNames =
Map.of(
"golang",
new SimpleEntry<>("go.mod", Optional.empty()),
"maven",
new SimpleEntry<>("pom.xml", Optional.empty()),
"npm",
new SimpleEntry<>("package.json", Optional.of(JavaScriptNpmProvider.LOCK_FILE)),
"pnpm",
new SimpleEntry<>("package.json", Optional.of(JavaScriptPnpmProvider.LOCK_FILE)),
"yarn",
new SimpleEntry<>("package.json", Optional.of(JavaScriptYarnProvider.LOCK_FILE)),
"pypi",
new SimpleEntry<>("requirements.txt", Optional.empty()),
"gradle-groovy",
new SimpleEntry<>("build.gradle", Optional.empty()),
"gradle-kotlin",
new SimpleEntry<>("build.gradle.kts", Optional.empty()));
}
private static List<Arguments> scenarios() {
return ecoSystemsManifestNames.entrySet().stream()
.map(e -> Arguments.of(e.getKey(), e.getValue().getKey(), e.getValue().getValue()))
.collect(Collectors.toList());
}
@Tag("IntegrationTest")
@ParameterizedTest(name = "StackAnalysis for: {0} with manifest: {1}")
@MethodSource("scenarios")
@RestoreSystemProperties
void Integration_Test_End_To_End_Stack_Analysis(
String useCase, String manifestFileName, Optional<String> lockFilename)
throws IOException, ExecutionException, InterruptedException {
Path manifestDirPath =
new TempDirFromResources()
.addFile(manifestFileName)
.fromResources(String.format("tst_manifests/it/%s/%s", useCase, manifestFileName))
.addFile(
lockFilename,
() -> String.format("tst_manifests/it/%s/%s", useCase, lockFilename.get()))
.getTempDir();
Path manifestFileNamePath = manifestDirPath.resolve(manifestFileName);
var provider = Ecosystem.getProvider(manifestFileNamePath);
var packageManager = provider.ecosystem;
preparePythonEnvironment(packageManager);
// Github action runner with all maven and java versions seems to enter infinite loop in
// integration tests of
// MAVEN when running dependency maven plugin to produce verbose text dependenct tree format.
// locally it's not recreated with same versions
mockMavenDependencyTree(packageManager);
AnalysisReport analysisReportResult = api.stackAnalysis(manifestFileNamePath.toString()).get();
handleJsonResponse(analysisReportResult, true);
releaseStaticMock(packageManager);
}
private void releaseStaticMock(Ecosystem.Type packageManager) {
if (packageManager.equals(Ecosystem.Type.MAVEN)) {
this.mockedOperations.close();
}
}
@Tag("IntegrationTest")
@ParameterizedTest(name = "StackAnalysis Mixed for: {0} with manifest: {1}")
@MethodSource("scenarios")
@RestoreSystemProperties
void Integration_Test_End_To_End_Stack_Analysis_Mixed(
String useCase, String manifestFileName, Optional<String> lockFilename)
throws IOException, ExecutionException, InterruptedException {
Path manifestDirPath =
new TempDirFromResources()
.addFile(manifestFileName)
.fromResources(String.format("tst_manifests/it/%s/%s", useCase, manifestFileName))
.addFile(
lockFilename,
() -> String.format("tst_manifests/it/%s/%s", useCase, lockFilename.get()))
.getTempDir();
Path manifestFileNamePath = manifestDirPath.resolve(manifestFileName);
String pathToManifest = manifestFileNamePath.toString();
var provider = Ecosystem.getProvider(Path.of(pathToManifest));
var packageManager = provider.ecosystem;
preparePythonEnvironment(packageManager);
// Github action runner with all maven and java versions seems to enter infinite loop in
// integration tests of
// MAVEN when runnig dependency maven plugin to produce verbose text dependenct tree format.
// locally it's not recreated with same versions
mockMavenDependencyTree(packageManager);
AnalysisReport analysisReportJson = api.stackAnalysisMixed(pathToManifest).get().json;
String analysisReportHtml = new String(api.stackAnalysisMixed(pathToManifest).get().html);
handleJsonResponse(analysisReportJson, true);
handleHtmlResponse(analysisReportHtml);
releaseStaticMock(packageManager);
}
@Tag("IntegrationTest")
@ParameterizedTest(name = "StackAnalysis HTML for: {0} with manifest: {1}")
@MethodSource("scenarios")
@RestoreSystemProperties
void Integration_Test_End_To_End_Stack_Analysis_Html(
String useCase, String manifestFileName, Optional<String> lockFilename)
throws IOException, ExecutionException, InterruptedException {
Path manifestDirPath =
new TempDirFromResources()
.addFile(manifestFileName)
.fromResources(String.format("tst_manifests/it/%s/%s", useCase, manifestFileName))
.addFile(
lockFilename,
() -> String.format("tst_manifests/it/%s/%s", useCase, lockFilename.get()))
.getTempDir();
Path manifestFileNamePath = manifestDirPath.resolve(manifestFileName);
String pathToManifest = manifestFileNamePath.toString();
var provider = Ecosystem.getProvider(Path.of(pathToManifest));
var packageManager = provider.ecosystem;
preparePythonEnvironment(packageManager);
// Github action runner with all maven and java versions seems to enter infinite loop in
// integration tests of
// MAVEN when running dependency maven plugin to produce verbose text dependenct tree format.
// locally it's not recreated with same versions
mockMavenDependencyTree(packageManager);
String analysisReportHtml = new String(api.stackAnalysisHtml(pathToManifest).get());
releaseStaticMock(packageManager);
handleHtmlResponse(analysisReportHtml);
}
@Tag("IntegrationTest")
@ParameterizedTest
@RestoreSystemProperties
@EnumSource(
value = Ecosystem.Type.class,
names = {"GOLANG", "MAVEN", "NPM", "PNPM", "YARN", "PYTHON"})
void Integration_Test_End_To_End_Component_Analysis(Ecosystem.Type packageManager)
throws IOException, ExecutionException, InterruptedException {
String manifestFileName = ecoSystemsManifestNames.get(packageManager.getType()).getKey();
Path tempDir =
new TempDirFromResources()
.addDirectory(
packageManager.getType(),
String.format("tst_manifests/it/%s", packageManager.getType()))
.getTempDir();
Path manifestPath = tempDir.resolve(packageManager.getType()).resolve(manifestFileName);
byte[] manifestContent = Files.readAllBytes(manifestPath);
preparePythonEnvironment(packageManager);
AnalysisReport analysisReportResult =
api.componentAnalysis(manifestPath.toString(), manifestContent).get();
handleJsonResponse(analysisReportResult, false);
}
@Tag("IntegrationTest")
@Test
@SetSystemProperty(key = SKIP_VALIDATION_KEY, value = "true")
void Integration_Test_End_To_End_Image_Analysis() throws IOException {
var result =
testImageAnalysis(
i -> {
try {
return api.imageAnalysis(i).get();
} catch (InterruptedException | ExecutionException | IOException e) {
throw new RuntimeException(e);
}
});
assertEquals(1, result.size());
handleJsonResponse(new ArrayList<>(result.values()).get(0), false);
}
@Tag("IntegrationTest")
@Test
@SetSystemProperty(key = SKIP_VALIDATION_KEY, value = "true")
void Integration_Test_End_To_End_Image_Analysis_Html() throws IOException {
var result =
testImageAnalysis(
i -> {
try {
return api.imageAnalysisHtml(i).get();
} catch (InterruptedException | ExecutionException | IOException e) {
throw new RuntimeException(e);
}
});
handleHtmlResponseForImage(new String(result));
}
private static <T> T testImageAnalysis(Function<Set<ImageRef>, T> imageAnalysisFunction)
throws IOException {
try (MockedStatic<Operations> mock = Mockito.mockStatic(Operations.class);
var sbomIS = getResourceAsStreamDecision(ExhortApiIT.class, "msc/image/image_sbom.json")) {
var imageRef =
new ImageRef(
"test.io/test/test-app:test-version@sha256:1fafb0905264413501df60d90a92ca32df8a2011cbfb4876ddff5ceb20c8f165",
"linux/amd64");
var jsonSbom =
new BufferedReader(new InputStreamReader(sbomIS, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
var output = new Operations.ProcessExecOutput(jsonSbom, "", 0);
mock.when(() -> Operations.getCustomPathOrElse(eq("syft"))).thenReturn("syft");
mock.when(() -> Operations.getExecutable(eq("syft"), any())).thenReturn("syft");
mock.when(
() ->
Operations.runProcessGetFullOutput(
isNull(),
aryEq(
new String[] {
"syft",
imageRef.getImage().getFullName(),
"-s",
"all-layers",
"-o",
"cyclonedx-json",
"-q"
}),
isNull()))
.thenReturn(output);
return imageAnalysisFunction.apply(Set.of(imageRef));
}
}
private static void preparePythonEnvironment(Ecosystem.Type packageManager) {
if (packageManager.equals(Ecosystem.Type.PYTHON)) {
System.setProperty(PROP_TRUSTIFY_DA_PYTHON_VIRTUAL_ENV, "true");
System.setProperty(PROP_TRUSTIFY_DA_PYTHON_INSTALL_BEST_EFFORTS, "true");
System.setProperty(PROP_MATCH_MANIFEST_VERSIONS, "false");
}
}
private static void handleJsonResponse(
AnalysisReport analysisReportResult, boolean positiveNumberOfTransitives) {
analysisReportResult.getProviders().entrySet().stream()
.forEach(
provider -> {
assertTrue(provider.getValue().getStatus().getOk());
assertThat(provider.getValue().getStatus().getCode())
.isEqualTo(HttpURLConnection.HTTP_OK);
});
analysisReportResult.getProviders().values().stream()
.map(ProviderReport::getSources)
.map(Map::entrySet)
.flatMap(Collection::stream)
.map(Map.Entry::getValue)
.forEach(source -> assertThat(source.getSummary().getTotal()).isGreaterThan(0));
if (positiveNumberOfTransitives) {
assertThat(analysisReportResult.getScanned().getTransitive()).isGreaterThan(0);
} else {
assertThat(analysisReportResult.getScanned().getTransitive()).isZero();
}
}
private void handleHtmlResponse(String analysisReportHtml) {
assertThat(analysisReportHtml).contains("svg", "html");
}
private void handleHtmlResponseForImage(String analysisReportHtml) {
assertThat(analysisReportHtml).contains("svg", "html");
}
private void mockMavenDependencyTree(Ecosystem.Type packageManager) throws IOException {
if (packageManager.equals(Ecosystem.Type.MAVEN)) {
mockedOperations = mockStatic(Operations.class);
String depTree;
try (var is = getResourceAsStreamDecision(getClass(), "tst_manifests/it/maven/depTree.txt")) {
depTree = new String(is.readAllBytes());
}
mockedOperations
.when(() -> Operations.runProcess(any(), any(), any()))
.thenAnswer(
invocationOnMock ->
getOutputFileAndOverwriteItWithMock(depTree, invocationOnMock, "-DoutputFile"));
mockedOperations
.when(() -> Operations.getCustomPathOrElse(anyString()))
.thenReturn(packageManager.getExecutableShortName());
mockedOperations
.when(() -> Operations.getExecutable(anyString(), anyString()))
.thenReturn(packageManager.getExecutableShortName());
}
}
public static String getOutputFileAndOverwriteItWithMock(
String outputFileContent, InvocationOnMock invocationOnMock, String parameterPrefix)
throws IOException {
String[] rawArguments = (String[]) invocationOnMock.getRawArguments()[1];
Optional<String> outputFileArg =
Arrays.stream(rawArguments)
.filter(arg -> arg != null && arg.startsWith(parameterPrefix))
.findFirst();
String outputFilePath = null;
if (outputFileArg.isPresent()) {
String outputFile = outputFileArg.get();
outputFilePath = outputFile.substring(outputFile.indexOf("=") + 1);
Files.writeString(Path.of(outputFilePath), outputFileContent);
}
return outputFilePath;
}
}