Search in sources :

Example 1 with ScanMetaData

use of com.amazonaws.gurureviewercli.model.ScanMetaData in project aws-codeguru-cli by aws.

the class Main method main.

public static void main(String[] argv) {
    val textIO = new TextIO(new SystemTextTerminal());
    val main = new Main();
    val jCommander = JCommander.newBuilder().addObject(main).build();
    if (argv.length == 0) {
        jCommander.usage();
        return;
    }
    try {
        jCommander.parse(argv);
        val config = Configuration.builder().textIO(textIO).interactiveMode(!main.noPrompt).bucketName(main.bucketName).build();
        main.validateInitialConfig(config);
        // try to build the AWS client objects first.
        main.createAWSClients(config);
        String repoName = config.getRootDir().toFile().getName();
        config.setRepoName(repoName);
        // check if repo is valid git.
        val gitMetaData = main.readGitMetaData(config, Paths.get(main.repoDir).toRealPath());
        ScanMetaData scanMetaData = null;
        List<RecommendationSummary> results = new ArrayList<>();
        try {
            val sourcePaths = main.sourceDirs.stream().map(Paths::get).map(Path::toAbsolutePath).map(Path::normalize).collect(Collectors.toList());
            List<Path> buildPaths = null;
            if (main.buildDirs != null) {
                buildPaths = main.buildDirs.stream().map(Paths::get).map(Path::toAbsolutePath).map(Path::normalize).collect(Collectors.toList());
            }
            scanMetaData = ScanAdapter.startScan(config, gitMetaData, sourcePaths, buildPaths);
            results.addAll(ScanAdapter.fetchResults(config, scanMetaData));
        } finally {
            if (scanMetaData != null) {
                // try to clean up objects from S3.
                main.tryDeleteS3Object(config.getS3Client(), scanMetaData.getBucketName(), scanMetaData.getSourceKey());
                main.tryDeleteS3Object(config.getS3Client(), scanMetaData.getBucketName(), scanMetaData.getBuildKey());
            }
        }
        val outputPath = Paths.get(main.outputDir);
        if (!outputPath.toFile().exists()) {
            if (!outputPath.toFile().mkdirs()) {
                Log.error("Failed to create output directory %s.", outputPath);
            }
        }
        ResultsAdapter.saveResults(outputPath, results, scanMetaData);
        Log.info("Analysis finished.");
    } catch (GuruCliException e) {
        Log.error("%s: %s", e.getErrorCode(), e.getMessage());
        e.printStackTrace();
        System.exit(3);
    } catch (ParameterException e) {
        Log.error(e);
        jCommander.usage();
        System.exit(1);
    } catch (Exception e) {
        e.printStackTrace();
        Log.error(e);
        System.exit(2);
    }
    System.exit(0);
}
Also used : lombok.val(lombok.val) Path(java.nio.file.Path) SystemTextTerminal(org.beryx.textio.system.SystemTextTerminal) ArrayList(java.util.ArrayList) TextIO(org.beryx.textio.TextIO) ParameterException(com.beust.jcommander.ParameterException) GuruCliException(com.amazonaws.gurureviewercli.exceptions.GuruCliException) IOException(java.io.IOException) SdkClientException(software.amazon.awssdk.core.exception.SdkClientException) ScanMetaData(com.amazonaws.gurureviewercli.model.ScanMetaData) RecommendationSummary(software.amazon.awssdk.services.codegurureviewer.model.RecommendationSummary) ParameterException(com.beust.jcommander.ParameterException) Paths(java.nio.file.Paths) GuruCliException(com.amazonaws.gurureviewercli.exceptions.GuruCliException)

Example 2 with ScanMetaData

use of com.amazonaws.gurureviewercli.model.ScanMetaData in project aws-codeguru-cli by aws.

the class ResultsAdapter method createHtmlReport.

private static void createHtmlReport(final Path outputDir, final ScanMetaData scanMetaData, final List<RecommendationSummary> recommendations) throws IOException {
    int validFindings = 0;
    // sort by file name and line number
    sortByFileName(recommendations);
    Parser parser = Parser.builder().build();
    HtmlRenderer renderer = HtmlRenderer.builder().build();
    val htmlFile = outputDir.resolve("codeguru-report.html");
    try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(htmlFile.toFile()), StandardCharsets.UTF_8)) {
        writer.write("<!DOCTYPE html>\n<html lang=\"en\">\n");
        writer.write("<body>\n");
        writer.write("<h2>CodeGuru Reviewer Recommendations</h2>\n");
        val awsUrlPrfix = "https://console.aws.amazon.com/codeguru/reviewer";
        val associationUrl = String.format("%s?region=%s#/ciworkflows/associationdetails/%s", awsUrlPrfix, scanMetaData.getRegion(), scanMetaData.getAssociationArn());
        val scanUrl = String.format("%s?region=%s#/codereviews/details/%s", awsUrlPrfix, scanMetaData.getRegion(), scanMetaData.getCodeReviewArn());
        writer.write(renderer.render(parser.parse(String.format("**CodeGuru Repository ARN**: [%s](%s)%n", scanMetaData.getAssociationArn(), associationUrl))));
        writer.write(renderer.render(parser.parse(String.format("**CodeGuru Scan ARN**: [%s](%s)%n", scanMetaData.getCodeReviewArn(), scanUrl))));
        writer.write("\n<br/><hr style=\"width:90%\"><br/>\n");
        for (val recommendation : recommendations) {
            val filePath = scanMetaData.getRepositoryRoot().resolve(recommendation.filePath()).toAbsolutePath();
            if (filePath == null || !filePath.toFile().isFile()) {
                if (filePath != null && !(filePath.endsWith(".") || filePath.endsWith("/"))) {
                    Log.warn("Dropping finding because file not found on disk: %s", filePath);
                }
                continue;
            }
            validFindings++;
            String lineMsg;
            if (!recommendation.startLine().equals(recommendation.endLine()) && recommendation.endLine() != null) {
                lineMsg = String.format("### In: [%s](%s) L%d %n", filePath, filePath.toUri(), recommendation.startLine());
            } else {
                lineMsg = String.format("### In: [%s](%s) L%d - L%d %n", filePath, filePath.toUri(), recommendation.startLine(), recommendation.endLine());
            }
            Node document = parser.parse(String.format("### In: [%s](%s) L%d %n", filePath, filePath.toUri(), recommendation.startLine()));
            writer.write(renderer.render(document));
            document = parser.parse("**Issue:** " + recommendation.description());
            writer.write(renderer.render(document));
            writer.write(String.format("<p><strong>Severity:</strong> %s<p/>", recommendation.severity()));
            if (recommendation.ruleMetadata() != null && recommendation.ruleMetadata().ruleId() != null) {
                val manifest = recommendation.ruleMetadata();
                writer.write(String.format("<p><strong>Rule ID:</strong> %s<p/>", manifest.ruleId()));
                writer.write(String.format("<p><strong>Rule Name:</strong> %s<p/>", manifest.ruleName()));
                document = parser.parse("**Description:** " + manifest.longDescription());
                writer.write(renderer.render(document));
                if (manifest.ruleTags() != null && !manifest.ruleTags().isEmpty()) {
                    val mdList = manifest.ruleTags().stream().map(s -> String.format("- %s%n", s)).collect(Collectors.joining());
                    document = parser.parse("**Tags:**\n" + mdList);
                    writer.write(renderer.render(document));
                }
            }
            writer.write("\n<hr style=\"width:80%\">\n");
        }
        writer.write("</body>\n");
        writer.write("</html>\n");
    }
    Log.info("Report with %d recommendations written to:%n%s", validFindings, htmlFile.normalize().toUri());
}
Also used : lombok.val(lombok.val) Arrays(java.util.Arrays) ArtifactLocation(com.contrastsecurity.sarif.ArtifactLocation) RecommendationSummary(software.amazon.awssdk.services.codegurureviewer.model.RecommendationSummary) ToolComponent(com.contrastsecurity.sarif.ToolComponent) HashMap(java.util.HashMap) ReportingDescriptor(com.contrastsecurity.sarif.ReportingDescriptor) ScanMetaData(com.amazonaws.gurureviewercli.model.ScanMetaData) Message(com.contrastsecurity.sarif.Message) HashSet(java.util.HashSet) Region(com.contrastsecurity.sarif.Region) Parser(org.commonmark.parser.Parser) Node(org.commonmark.node.Node) Map(java.util.Map) OutputStreamWriter(java.io.OutputStreamWriter) Run(com.contrastsecurity.sarif.Run) URI(java.net.URI) Path(java.nio.file.Path) Location(com.contrastsecurity.sarif.Location) Log(com.amazonaws.gurureviewercli.util.Log) lombok.val(lombok.val) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) HtmlRenderer(org.commonmark.renderer.html.HtmlRenderer) PropertyBag(com.contrastsecurity.sarif.PropertyBag) Tool(com.contrastsecurity.sarif.Tool) ReportingConfiguration(com.contrastsecurity.sarif.ReportingConfiguration) JsonUtil(com.amazonaws.gurureviewercli.util.JsonUtil) Collections(java.util.Collections) MultiformatMessageString(com.contrastsecurity.sarif.MultiformatMessageString) PhysicalLocation(com.contrastsecurity.sarif.PhysicalLocation) Result(com.contrastsecurity.sarif.Result) SarifSchema210(com.contrastsecurity.sarif.SarifSchema210) FileOutputStream(java.io.FileOutputStream) Node(org.commonmark.node.Node) HtmlRenderer(org.commonmark.renderer.html.HtmlRenderer) OutputStreamWriter(java.io.OutputStreamWriter) MultiformatMessageString(com.contrastsecurity.sarif.MultiformatMessageString) Parser(org.commonmark.parser.Parser)

Aggregations

ScanMetaData (com.amazonaws.gurureviewercli.model.ScanMetaData)2 IOException (java.io.IOException)2 Path (java.nio.file.Path)2 lombok.val (lombok.val)2 RecommendationSummary (software.amazon.awssdk.services.codegurureviewer.model.RecommendationSummary)2 GuruCliException (com.amazonaws.gurureviewercli.exceptions.GuruCliException)1 JsonUtil (com.amazonaws.gurureviewercli.util.JsonUtil)1 Log (com.amazonaws.gurureviewercli.util.Log)1 ParameterException (com.beust.jcommander.ParameterException)1 ArtifactLocation (com.contrastsecurity.sarif.ArtifactLocation)1 Location (com.contrastsecurity.sarif.Location)1 Message (com.contrastsecurity.sarif.Message)1 MultiformatMessageString (com.contrastsecurity.sarif.MultiformatMessageString)1 PhysicalLocation (com.contrastsecurity.sarif.PhysicalLocation)1 PropertyBag (com.contrastsecurity.sarif.PropertyBag)1 Region (com.contrastsecurity.sarif.Region)1 ReportingConfiguration (com.contrastsecurity.sarif.ReportingConfiguration)1 ReportingDescriptor (com.contrastsecurity.sarif.ReportingDescriptor)1 Result (com.contrastsecurity.sarif.Result)1 Run (com.contrastsecurity.sarif.Run)1