Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for YAML as an output format #1401

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/scan/scan.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func GetScanCommand(ks meta.IKubescape) *cobra.Command {
scanCmd.PersistentFlags().Float32VarP(&scanInfo.ComplianceThreshold, "compliance-threshold", "", 0, "Compliance threshold is the percent below which the command fails and returns exit code 1")

scanCmd.PersistentFlags().StringVar(&scanInfo.FailThresholdSeverity, "severity-threshold", "", "Severity threshold is the severity of failed controls at which the command fails and returns exit code 1")
scanCmd.PersistentFlags().StringVarP(&scanInfo.Format, "format", "f", "", `Output file format. Supported formats: "pretty-printer", "json", "junit", "prometheus", "pdf", "html", "sarif"`)
scanCmd.PersistentFlags().StringVarP(&scanInfo.Format, "format", "f", "", `Output file format. Supported formats: "pretty-printer", "json", "junit", "prometheus", "pdf", "html", "sarif", "yaml"`)
scanCmd.PersistentFlags().StringVar(&scanInfo.IncludeNamespaces, "include-namespaces", "", "scan specific namespaces. e.g: --include-namespaces ns-a,ns-b")
scanCmd.PersistentFlags().BoolVarP(&scanInfo.Local, "keep-local", "", false, "If you do not want your Kubescape results reported to configured backend.")
scanCmd.PersistentFlags().StringVarP(&scanInfo.Output, "output", "o", "", "Output file. Print output to file and not stdout")
Expand Down
1 change: 1 addition & 0 deletions core/pkg/resultshandling/printer/printresults.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const (
PdfFormat string = "pdf"
HtmlFormat string = "html"
SARIFFormat string = "sarif"
YamlFormat string = "yaml"
)

type IPrinter interface {
Expand Down
128 changes: 128 additions & 0 deletions core/pkg/resultshandling/printer/v2/yamlprinter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package printer

import (
"context"
"encoding/json"
"sigs.k8s.io/yaml"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"

"github.com/anchore/grype/grype/presenter"
"github.com/anchore/grype/grype/presenter/models"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/pkg/resultshandling/printer"
)

const (
yamlOutputFile = "report"
yamlOutputExt = ".yaml"
)

var _ printer.IPrinter = &YamlPrinter{}

type YamlPrinter struct {
writer *os.File
}

func NewYamlPrinter() *YamlPrinter {
return &YamlPrinter{}
}

func (yp *YamlPrinter) SetWriter(ctx context.Context, outputFile string) {
if strings.TrimSpace(outputFile) == "" {
outputFile = yamlOutputFile
}
if filepath.Ext(strings.TrimSpace(outputFile)) != yamlOutputExt {
outputFile = outputFile + yamlOutputExt
}
yp.writer = printer.GetWriter(ctx, outputFile)
}

func (yp *YamlPrinter) Score(score float32) {
fmt.Fprintf(os.Stderr, "\nOverall compliance-score (100- Excellent, 0- All failed): %d\n", cautils.Float32ToInt(score))

}

func jsonToYAML() () {
// Convert the JSON data in the report.yaml file to YAML data.
fileName := yamlOutputFile + yamlOutputExt;
jsonData, err := ioutil.ReadFile(fileName)
if err != nil {
fmt.Printf("Error reading file: %v\n", err)
return
}

var data interface{}

if err := yaml.Unmarshal(jsonData, &data); err != nil {
return
}

yamlData, err := yaml.Marshal(data)
if err != nil {
return
}

// Overwrite the file with the new YAML content
err = ioutil.WriteFile(fileName, yamlData, os.ModePerm)
if err != nil {
fmt.Printf("Error writing YAML to file: %v\n", err)
return
}
}

func (yp *YamlPrinter) ActionPrint(ctx context.Context, opaSessionObj *cautils.OPASessionObj, imageScanData []cautils.ImageScanData) {
var err error
if opaSessionObj != nil {
err = printYamlConfigurationsScanning(opaSessionObj, ctx, yp)
} else if imageScanData != nil {
err = yp.PrintImageScan(ctx, imageScanData[0].PresenterConfig)
} else {
err = fmt.Errorf("no data provided")
}

if err != nil {
logger.L().Ctx(ctx).Error("failed to write results in yaml format", helpers.Error(err))
return
}

// Convert JSON to YAML
jsonToYAML()

printer.LogOutputFile(yp.writer.Name())
}

func printYamlConfigurationsScanning(opaSessionObj *cautils.OPASessionObj, ctx context.Context, yp *YamlPrinter) error {
r, err := json.Marshal(FinalizeResults(opaSessionObj))
if err != nil {
return err
}

_, err = yp.writer.Write(r)
return err
}

func (yp *YamlPrinter) PrintImageScan(ctx context.Context, scanResults *models.PresenterConfig) error {
if scanResults == nil {
return fmt.Errorf("no image vulnerability data provided")
}

// Since grype/presenter doesn't have yaml config, use JSON config.
presenterConfig, err := presenter.ValidatedConfig("json", "", false)
if err != nil {
return err
}

pres := presenter.GetPresenter(presenterConfig, *scanResults)

return pres.Present(yp.writer)
}

func (yp *YamlPrinter) PrintNextSteps() {

}
4 changes: 3 additions & 1 deletion core/pkg/resultshandling/results.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@ func NewPrinter(ctx context.Context, printFormat, formatVersion string, verboseM
return printerv2.NewHtmlPrinter()
case printer.SARIFFormat:
return printerv2.NewSARIFPrinter()
case printer.YamlFormat:
return printerv2.NewYamlPrinter()
default:
if printFormat != printer.PrettyFormat {
logger.L().Ctx(ctx).Warning(fmt.Sprintf("Invalid format \"%s\", default format \"pretty-printer\" is applied", printFormat))
Expand All @@ -136,7 +138,7 @@ func ValidatePrinter(scanType cautils.ScanTypes, scanContext cautils.ScanningCon
if scanType == cautils.ScanTypeImage {
// supported types for image scanning
switch printFormat {
case printer.JsonFormat, printer.PrettyFormat, printer.SARIFFormat:
case printer.JsonFormat, printer.PrettyFormat, printer.SARIFFormat, printer.YamlFormat:
return nil
default:
return fmt.Errorf("format \"%s\"is not supported for image scanning", printFormat)
Expand Down