forked from guacsec/trustify-da-java-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.java
More file actions
401 lines (356 loc) · 14 KB
/
Copy pathApp.java
File metadata and controls
401 lines (356 loc) · 14 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
396
397
398
399
400
401
/*
* 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.cli;
import static io.github.guacsec.trustifyda.cli.AppUtils.exitWithError;
import static io.github.guacsec.trustifyda.cli.AppUtils.printException;
import static io.github.guacsec.trustifyda.cli.AppUtils.printLine;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.guacsec.trustifyda.Api;
import io.github.guacsec.trustifyda.Provider;
import io.github.guacsec.trustifyda.api.v5.AnalysisReport;
import io.github.guacsec.trustifyda.api.v5.ProviderReport;
import io.github.guacsec.trustifyda.api.v5.SourceSummary;
import io.github.guacsec.trustifyda.image.ImageRef;
import io.github.guacsec.trustifyda.image.ImageUtils;
import io.github.guacsec.trustifyda.impl.ExhortApi;
import io.github.guacsec.trustifyda.license.ProjectLicense;
import io.github.guacsec.trustifyda.license.ProjectLicense.ProjectLicenseInfo;
import io.github.guacsec.trustifyda.tools.Ecosystem;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class App {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String CLI_HELPTXT = "cli_help.txt";
static {
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
public static void main(String[] args) {
if (args.length == 0 || isHelpRequested(args)) {
printHelp();
return;
}
try {
CliArgs cliArgs = parseArgs(args);
String result = executeCommand(cliArgs).get();
printLine(result);
} catch (IllegalArgumentException e) {
printException(e);
printHelp();
exitWithError();
} catch (IOException | InterruptedException | ExecutionException e) {
printException(e);
exitWithError();
}
}
private static boolean isHelpRequested(String[] args) {
for (String arg : args) {
if ("--help".equals(arg) || "-h".equals(arg)) {
return true;
}
}
return false;
}
private static CliArgs parseArgs(String[] args) {
if (args.length < 2) {
throw new IllegalArgumentException("Missing required arguments");
}
Command command = parseCommand(args[0]);
return switch (command) {
case STACK, COMPONENT, LICENSE -> parseFileBasedArgs(command, args);
case IMAGE -> parseImageBasedArgs(command, args);
case SBOM -> parseSbomArgs(args);
};
}
private static CliArgs parseFileBasedArgs(Command command, String[] args) {
if (args.length < 2) {
throw new IllegalArgumentException("Missing required file path for " + command + " command");
}
Path path = validateFile(args[1]);
OutputFormat outputFormat = OutputFormat.JSON;
if (args.length == 3) {
if (command == Command.LICENSE) {
throw new IllegalArgumentException("license command does not accept options");
}
outputFormat = parseOutputFormat(command, args[2]);
} else if (args.length > 3) {
throw new IllegalArgumentException("Too many arguments for " + command + " command");
}
return new CliArgs(command, path, outputFormat);
}
private static CliArgs parseImageBasedArgs(Command command, String[] args) {
if (args.length < 2) {
throw new IllegalArgumentException(
"Missing required image references for " + command + " command");
}
OutputFormat outputFormat = OutputFormat.JSON;
int imageArgCount = args.length - 1;
if (args.length >= 3) {
String lastArg = args[args.length - 1];
if (lastArg.startsWith("--")) {
outputFormat = parseOutputFormat(command, lastArg);
imageArgCount = args.length - 2;
}
}
if (imageArgCount < 1) {
throw new IllegalArgumentException(
"At least one image reference is required for " + command + " command");
}
Set<ImageRef> imageRefs = new HashSet<>();
for (int i = 1; i <= imageArgCount; i++) {
try {
ImageRef imageRef = ImageUtils.parseImageRef(args[i]);
imageRefs.add(imageRef);
} catch (Exception e) {
throw new IllegalArgumentException(
"Invalid image reference '" + args[i] + "': " + e.getMessage(), e);
}
}
return new CliArgs(command, imageRefs, outputFormat);
}
private static CliArgs parseSbomArgs(String[] args) {
if (args.length < 2) {
throw new IllegalArgumentException("Missing required file path for sbom command");
}
Path path = validateFile(args[1]);
Path outputPath = null;
for (int i = 2; i < args.length; i++) {
if ("--output".equals(args[i])) {
if (i + 1 >= args.length) {
throw new IllegalArgumentException("Missing value for --output flag");
}
outputPath = Paths.get(args[++i]);
} else {
throw new IllegalArgumentException("Unknown option for sbom command: " + args[i]);
}
}
return new CliArgs(Command.SBOM, path, outputPath);
}
private static Command parseCommand(String commandStr) {
return switch (commandStr) {
case "stack" -> Command.STACK;
case "component" -> Command.COMPONENT;
case "image" -> Command.IMAGE;
case "license" -> Command.LICENSE;
case "sbom" -> Command.SBOM;
default ->
throw new IllegalArgumentException(
"Unknown command: "
+ commandStr
+ ". Use 'stack', 'component', 'image', 'license', or 'sbom'");
};
}
private static OutputFormat parseOutputFormat(Command command, String formatArg) {
return switch (formatArg) {
case "--summary" -> OutputFormat.SUMMARY;
case "--html" -> {
if (command != Command.STACK && command != Command.IMAGE) {
throw new IllegalArgumentException(
"HTML format is only supported for stack and image commands");
}
yield OutputFormat.HTML;
}
default ->
throw new IllegalArgumentException(
"Unknown option for " + command + " command: " + formatArg);
};
}
private static Path validateFile(String filePath) {
Path path = Paths.get(filePath);
if (!Files.exists(path)) {
throw new IllegalArgumentException("File does not exist: " + filePath);
}
if (!Files.isRegularFile(path)) {
throw new IllegalArgumentException("File is not a regular file: " + filePath);
}
return path;
}
private static CompletableFuture<String> executeCommand(CliArgs args) throws IOException {
return switch (args.command) {
case STACK ->
executeStackAnalysis(args.filePath.toAbsolutePath().toString(), args.outputFormat);
case COMPONENT ->
executeComponentAnalysis(args.filePath.toAbsolutePath().toString(), args.outputFormat);
case IMAGE -> executeImageAnalysis(args.imageRefs, args.outputFormat);
case LICENSE -> executeLicenseCheck(args.filePath.toAbsolutePath());
case SBOM -> executeSbomGeneration(args);
};
}
private static CompletableFuture<String> executeStackAnalysis(
String filePath, OutputFormat outputFormat) throws IOException {
Api api = new ExhortApi();
return switch (outputFormat) {
case JSON -> api.stackAnalysis(filePath).thenApply(App::toJsonString);
case HTML -> api.stackAnalysisHtml(filePath).thenApply(bytes -> new String(bytes));
case SUMMARY ->
api.stackAnalysis(filePath).thenApply(App::extractSummary).thenApply(App::toJsonString);
};
}
private static CompletableFuture<String> executeComponentAnalysis(
String filePath, OutputFormat outputFormat) throws IOException {
ExhortApi api = new ExhortApi();
if (outputFormat.equals(OutputFormat.SUMMARY)) {
return api.componentAnalysis(filePath)
.thenApply(App::extractSummary)
.thenApply(App::toJsonString);
}
return api.componentAnalysisWithLicense(filePath)
.thenApply(
result -> {
@SuppressWarnings("unchecked")
Map<String, Object> flat = MAPPER.convertValue(result.report(), Map.class);
if (result.licenseSummary() != null) {
flat.put("licenseSummary", result.licenseSummary());
}
return toJsonString(flat);
});
}
private static CompletableFuture<String> executeLicenseCheck(Path manifestPath) {
ExhortApi api = new ExhortApi();
Provider provider = Ecosystem.getProvider(manifestPath);
ProjectLicenseInfo localResult = ProjectLicense.getProjectLicense(provider, manifestPath);
CompletableFuture<Map<String, Object>> manifestDetailsFuture =
buildLicenseInfo(api, localResult.fromManifest());
CompletableFuture<Map<String, Object>> fileDetailsFuture =
buildLicenseInfo(api, localResult.fromFile());
return manifestDetailsFuture.thenCombine(
fileDetailsFuture,
(manifestInfo, fileInfo) -> {
Map<String, Object> output = new LinkedHashMap<>();
output.put("manifestLicense", manifestInfo);
output.put("fileLicense", fileInfo);
output.put("mismatch", localResult.mismatch());
return toJsonString(output);
});
}
private static CompletableFuture<Map<String, Object>> buildLicenseInfo(
ExhortApi api, String spdxId) {
if (spdxId == null) {
return CompletableFuture.completedFuture(null);
}
Map<String, Object> licenseInfo = new HashMap<>();
licenseInfo.put("spdxId", spdxId);
return api.getLicenseDetails(spdxId)
.thenApply(
details -> {
if (details != null) {
licenseInfo.put("details", details);
}
return licenseInfo;
})
.exceptionally(
ex -> {
licenseInfo.put("error", ex.getMessage());
return licenseInfo;
});
}
private static String toJsonString(Object obj) {
try {
return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException("Failed to serialize to JSON", e);
}
}
private static CompletableFuture<String> executeImageAnalysis(
Set<ImageRef> imageRefs, OutputFormat outputFormat) throws IOException {
Api api = new ExhortApi();
return switch (outputFormat) {
case JSON -> api.imageAnalysis(imageRefs).thenApply(App::formatImageAnalysisResult);
case HTML -> api.imageAnalysisHtml(imageRefs).thenApply(bytes -> new String(bytes));
case SUMMARY ->
api.imageAnalysis(imageRefs)
.thenApply(App::extractImageSummary)
.thenApply(App::toJsonString);
};
}
private static CompletableFuture<String> executeSbomGeneration(CliArgs args) throws IOException {
Api api = new ExhortApi();
String sbomJson = api.generateSbom(args.filePath.toAbsolutePath().toString());
if (args.outputPath != null) {
Files.writeString(args.outputPath, sbomJson);
return CompletableFuture.completedFuture(
"SBOM written to " + args.outputPath.toAbsolutePath());
}
return CompletableFuture.completedFuture(sbomJson);
}
private static String formatImageAnalysisResult(Map<ImageRef, AnalysisReport> analysisResults) {
try {
return MAPPER.writeValueAsString(analysisResults);
} catch (JsonProcessingException e) {
throw new RuntimeException("Failed to serialize image analysis results", e);
}
}
private static Map<String, Map<String, SourceSummary>> extractImageSummary(
Map<ImageRef, AnalysisReport> analysisResults) {
Map<String, Map<String, SourceSummary>> imageSummaries = new HashMap<>();
for (Map.Entry<ImageRef, AnalysisReport> entry : analysisResults.entrySet()) {
String imageKey = entry.getKey().toString();
Map<String, SourceSummary> imageSummary = extractSummary(entry.getValue());
imageSummaries.put(imageKey, imageSummary);
}
return imageSummaries;
}
private static Map<String, SourceSummary> extractSummary(AnalysisReport report) {
Map<String, SourceSummary> summary = new HashMap<>();
if (report.getProviders() == null) {
return summary;
}
report
.getProviders()
.entrySet()
.forEach(
entry -> {
var provider = new ProviderReport();
provider.setStatus(entry.getValue().getStatus());
if (entry.getValue().getSources() != null) {
entry
.getValue()
.getSources()
.entrySet()
.forEach(
sourceEntry -> {
if (sourceEntry.getValue().getSummary() != null) {
summary.put(sourceEntry.getKey(), sourceEntry.getValue().getSummary());
}
});
}
});
return summary;
}
private static void printHelp() {
try (var inputStream = App.class.getClassLoader().getResourceAsStream(CLI_HELPTXT)) {
if (inputStream == null) {
AppUtils.printError("Help file not found.");
return;
}
String helpText = new String(inputStream.readAllBytes());
printLine(helpText);
} catch (IOException e) {
AppUtils.printError("Error reading help file: " + e.getMessage());
}
}
}