github.com/xgoffin/jenkins-library@v1.154.0/cmd/malwareExecuteScan_generated.go (about)

     1  // Code generated by piper's step-generator. DO NOT EDIT.
     2  
     3  package cmd
     4  
     5  import (
     6  	"fmt"
     7  	"os"
     8  	"reflect"
     9  	"strings"
    10  	"time"
    11  
    12  	"github.com/SAP/jenkins-library/pkg/config"
    13  	"github.com/SAP/jenkins-library/pkg/gcs"
    14  	"github.com/SAP/jenkins-library/pkg/log"
    15  	"github.com/SAP/jenkins-library/pkg/splunk"
    16  	"github.com/SAP/jenkins-library/pkg/telemetry"
    17  	"github.com/SAP/jenkins-library/pkg/validation"
    18  	"github.com/bmatcuk/doublestar"
    19  	"github.com/spf13/cobra"
    20  )
    21  
    22  type malwareExecuteScanOptions struct {
    23  	BuildTool                 string `json:"buildTool,omitempty"`
    24  	DockerConfigJSON          string `json:"dockerConfigJSON,omitempty"`
    25  	ContainerRegistryPassword string `json:"containerRegistryPassword,omitempty"`
    26  	ContainerRegistryUser     string `json:"containerRegistryUser,omitempty"`
    27  	Host                      string `json:"host,omitempty"`
    28  	Username                  string `json:"username,omitempty"`
    29  	Password                  string `json:"password,omitempty"`
    30  	ScanImage                 string `json:"scanImage,omitempty"`
    31  	ScanImageIncludeLayers    bool   `json:"scanImageIncludeLayers,omitempty"`
    32  	ScanImageRegistryURL      string `json:"scanImageRegistryUrl,omitempty"`
    33  	ScanFile                  string `json:"scanFile,omitempty"`
    34  	Timeout                   string `json:"timeout,omitempty"`
    35  	ReportFileName            string `json:"reportFileName,omitempty"`
    36  }
    37  
    38  type malwareExecuteScanReports struct {
    39  }
    40  
    41  func (p *malwareExecuteScanReports) persist(stepConfig malwareExecuteScanOptions, gcpJsonKeyFilePath string, gcsBucketId string, gcsFolderPath string, gcsSubFolder string) {
    42  	if gcsBucketId == "" {
    43  		log.Entry().Info("persisting reports to GCS is disabled, because gcsBucketId is empty")
    44  		return
    45  	}
    46  	log.Entry().Info("Uploading reports to Google Cloud Storage...")
    47  	content := []gcs.ReportOutputParam{
    48  		{FilePattern: "**/toolrun_malwarescan_*.json", ParamRef: "", StepResultType: "malwarescan"},
    49  		{FilePattern: "", ParamRef: "reportFileName", StepResultType: "malwarescan"},
    50  	}
    51  	envVars := []gcs.EnvVar{
    52  		{Name: "GOOGLE_APPLICATION_CREDENTIALS", Value: gcpJsonKeyFilePath, Modified: false},
    53  	}
    54  	gcsClient, err := gcs.NewClient(gcs.WithEnvVars(envVars))
    55  	if err != nil {
    56  		log.Entry().Errorf("creation of GCS client failed: %v", err)
    57  		return
    58  	}
    59  	defer gcsClient.Close()
    60  	structVal := reflect.ValueOf(&stepConfig).Elem()
    61  	inputParameters := map[string]string{}
    62  	for i := 0; i < structVal.NumField(); i++ {
    63  		field := structVal.Type().Field(i)
    64  		if field.Type.String() == "string" {
    65  			paramName := strings.Split(field.Tag.Get("json"), ",")
    66  			paramValue, _ := structVal.Field(i).Interface().(string)
    67  			inputParameters[paramName[0]] = paramValue
    68  		}
    69  	}
    70  	if err := gcs.PersistReportsToGCS(gcsClient, content, inputParameters, gcsFolderPath, gcsBucketId, gcsSubFolder, doublestar.Glob, os.Stat); err != nil {
    71  		log.Entry().Errorf("failed to persist reports: %v", err)
    72  	}
    73  }
    74  
    75  // MalwareExecuteScanCommand Performs a malware scan using the [SAP Malware Scanning Service](https://help.sap.com/viewer/b416237f818c4e2e827f6118640079f8/LATEST/en-US/b7c9b86fe724458086a502df3160f380.html).
    76  func MalwareExecuteScanCommand() *cobra.Command {
    77  	const STEP_NAME = "malwareExecuteScan"
    78  
    79  	metadata := malwareExecuteScanMetadata()
    80  	var stepConfig malwareExecuteScanOptions
    81  	var startTime time.Time
    82  	var reports malwareExecuteScanReports
    83  	var logCollector *log.CollectorHook
    84  	var splunkClient *splunk.Splunk
    85  	telemetryClient := &telemetry.Telemetry{}
    86  
    87  	var createMalwareExecuteScanCmd = &cobra.Command{
    88  		Use:   STEP_NAME,
    89  		Short: "Performs a malware scan using the [SAP Malware Scanning Service](https://help.sap.com/viewer/b416237f818c4e2e827f6118640079f8/LATEST/en-US/b7c9b86fe724458086a502df3160f380.html).",
    90  		Long:  `Performs a malware scan using the [SAP Malware Scanning Service](https://help.sap.com/viewer/b416237f818c4e2e827f6118640079f8/LATEST/en-US/b7c9b86fe724458086a502df3160f380.html).`,
    91  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    92  			startTime = time.Now()
    93  			log.SetStepName(STEP_NAME)
    94  			log.SetVerbose(GeneralConfig.Verbose)
    95  
    96  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    97  
    98  			path, _ := os.Getwd()
    99  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
   100  			log.RegisterHook(fatalHook)
   101  
   102  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
   103  			if err != nil {
   104  				log.SetErrorCategory(log.ErrorConfiguration)
   105  				return err
   106  			}
   107  			log.RegisterSecret(stepConfig.DockerConfigJSON)
   108  			log.RegisterSecret(stepConfig.ContainerRegistryPassword)
   109  			log.RegisterSecret(stepConfig.ContainerRegistryUser)
   110  			log.RegisterSecret(stepConfig.Username)
   111  			log.RegisterSecret(stepConfig.Password)
   112  
   113  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
   114  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
   115  				log.RegisterHook(&sentryHook)
   116  			}
   117  
   118  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   119  				splunkClient = &splunk.Splunk{}
   120  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
   121  				log.RegisterHook(logCollector)
   122  			}
   123  
   124  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
   125  			if err != nil {
   126  				return err
   127  			}
   128  			if err = validation.ValidateStruct(stepConfig); err != nil {
   129  				log.SetErrorCategory(log.ErrorConfiguration)
   130  				return err
   131  			}
   132  
   133  			return nil
   134  		},
   135  		Run: func(_ *cobra.Command, _ []string) {
   136  			stepTelemetryData := telemetry.CustomData{}
   137  			stepTelemetryData.ErrorCode = "1"
   138  			handler := func() {
   139  				reports.persist(stepConfig, GeneralConfig.GCPJsonKeyFilePath, GeneralConfig.GCSBucketId, GeneralConfig.GCSFolderPath, GeneralConfig.GCSSubFolder)
   140  				config.RemoveVaultSecretFiles()
   141  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   142  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   143  				stepTelemetryData.PiperCommitHash = GitCommit
   144  				telemetryClient.SetData(&stepTelemetryData)
   145  				telemetryClient.Send()
   146  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   147  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   148  				}
   149  			}
   150  			log.DeferExitHandler(handler)
   151  			defer handler()
   152  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   153  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   154  				splunkClient.Initialize(GeneralConfig.CorrelationID,
   155  					GeneralConfig.HookConfig.SplunkConfig.Dsn,
   156  					GeneralConfig.HookConfig.SplunkConfig.Token,
   157  					GeneralConfig.HookConfig.SplunkConfig.Index,
   158  					GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   159  			}
   160  			malwareExecuteScan(stepConfig, &stepTelemetryData)
   161  			stepTelemetryData.ErrorCode = "0"
   162  			log.Entry().Info("SUCCESS")
   163  		},
   164  	}
   165  
   166  	addMalwareExecuteScanFlags(createMalwareExecuteScanCmd, &stepConfig)
   167  	return createMalwareExecuteScanCmd
   168  }
   169  
   170  func addMalwareExecuteScanFlags(cmd *cobra.Command, stepConfig *malwareExecuteScanOptions) {
   171  	cmd.Flags().StringVar(&stepConfig.BuildTool, "buildTool", os.Getenv("PIPER_buildTool"), "Defines the tool which is used for building the artifact.")
   172  	cmd.Flags().StringVar(&stepConfig.DockerConfigJSON, "dockerConfigJSON", os.Getenv("PIPER_dockerConfigJSON"), "Path to the file `.docker/config.json` - this is typically provided by your CI/CD system. You can find more details about the Docker credentials in the [Docker documentation](https://docs.docker.com/engine/reference/commandline/login/).")
   173  	cmd.Flags().StringVar(&stepConfig.ContainerRegistryPassword, "containerRegistryPassword", os.Getenv("PIPER_containerRegistryPassword"), "For `buildTool: docker`: Password for container registry access - typically provided by the CI/CD environment.")
   174  	cmd.Flags().StringVar(&stepConfig.ContainerRegistryUser, "containerRegistryUser", os.Getenv("PIPER_containerRegistryUser"), "For `buildTool: docker`: Username for container registry access - typically provided by the CI/CD environment.")
   175  	cmd.Flags().StringVar(&stepConfig.Host, "host", os.Getenv("PIPER_host"), "malware scanning host.")
   176  	cmd.Flags().StringVar(&stepConfig.Username, "username", os.Getenv("PIPER_username"), "User")
   177  	cmd.Flags().StringVar(&stepConfig.Password, "password", os.Getenv("PIPER_password"), "Password")
   178  	cmd.Flags().StringVar(&stepConfig.ScanImage, "scanImage", os.Getenv("PIPER_scanImage"), "For `buildTool: docker`: Defines the docker image which should be scanned.")
   179  	cmd.Flags().BoolVar(&stepConfig.ScanImageIncludeLayers, "scanImageIncludeLayers", true, "For `buildTool: docker`: Defines if layers should be included.")
   180  	cmd.Flags().StringVar(&stepConfig.ScanImageRegistryURL, "scanImageRegistryUrl", os.Getenv("PIPER_scanImageRegistryUrl"), "For `buildTool: docker`: Defines the registry where the scanImage is located.")
   181  	cmd.Flags().StringVar(&stepConfig.ScanFile, "scanFile", os.Getenv("PIPER_scanFile"), "The file which is scanned for malware")
   182  	cmd.Flags().StringVar(&stepConfig.Timeout, "timeout", `600`, "timeout for http layer in seconds")
   183  	cmd.Flags().StringVar(&stepConfig.ReportFileName, "reportFileName", `malwarescan_report.json`, "The file name of the report to be created")
   184  
   185  	cmd.MarkFlagRequired("buildTool")
   186  	cmd.MarkFlagRequired("host")
   187  	cmd.MarkFlagRequired("username")
   188  	cmd.MarkFlagRequired("password")
   189  }
   190  
   191  // retrieve step metadata
   192  func malwareExecuteScanMetadata() config.StepData {
   193  	var theMetaData = config.StepData{
   194  		Metadata: config.StepMetadata{
   195  			Name:        "malwareExecuteScan",
   196  			Aliases:     []config.Alias{},
   197  			Description: "Performs a malware scan using the [SAP Malware Scanning Service](https://help.sap.com/viewer/b416237f818c4e2e827f6118640079f8/LATEST/en-US/b7c9b86fe724458086a502df3160f380.html).",
   198  		},
   199  		Spec: config.StepSpec{
   200  			Inputs: config.StepInputs{
   201  				Secrets: []config.StepSecrets{
   202  					{Name: "malwareScanCredentialsId", Description: "Jenkins 'Username with password' credentials ID containing the technical user/password credential used to communicate with the malwarescanning service.", Type: "jenkins"},
   203  				},
   204  				Parameters: []config.StepParameters{
   205  					{
   206  						Name: "buildTool",
   207  						ResourceRef: []config.ResourceReference{
   208  							{
   209  								Name:  "commonPipelineEnvironment",
   210  								Param: "buildTool",
   211  							},
   212  						},
   213  						Scope:     []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   214  						Type:      "string",
   215  						Mandatory: true,
   216  						Aliases:   []config.Alias{},
   217  						Default:   os.Getenv("PIPER_buildTool"),
   218  					},
   219  					{
   220  						Name: "dockerConfigJSON",
   221  						ResourceRef: []config.ResourceReference{
   222  							{
   223  								Name:  "commonPipelineEnvironment",
   224  								Param: "custom/dockerConfigJSON",
   225  							},
   226  
   227  							{
   228  								Name: "dockerConfigJsonCredentialsId",
   229  								Type: "secret",
   230  							},
   231  
   232  							{
   233  								Name:    "dockerConfigFileVaultSecretName",
   234  								Type:    "vaultSecretFile",
   235  								Default: "docker-config",
   236  							},
   237  						},
   238  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   239  						Type:      "string",
   240  						Mandatory: false,
   241  						Aliases:   []config.Alias{},
   242  						Default:   os.Getenv("PIPER_dockerConfigJSON"),
   243  					},
   244  					{
   245  						Name: "containerRegistryPassword",
   246  						ResourceRef: []config.ResourceReference{
   247  							{
   248  								Name:  "commonPipelineEnvironment",
   249  								Param: "container/repositoryPassword",
   250  							},
   251  
   252  							{
   253  								Name:  "commonPipelineEnvironment",
   254  								Param: "custom/repositoryPassword",
   255  							},
   256  						},
   257  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   258  						Type:      "string",
   259  						Mandatory: false,
   260  						Aliases:   []config.Alias{},
   261  						Default:   os.Getenv("PIPER_containerRegistryPassword"),
   262  					},
   263  					{
   264  						Name: "containerRegistryUser",
   265  						ResourceRef: []config.ResourceReference{
   266  							{
   267  								Name:  "commonPipelineEnvironment",
   268  								Param: "container/repositoryUsername",
   269  							},
   270  
   271  							{
   272  								Name:  "commonPipelineEnvironment",
   273  								Param: "custom/repositoryUsername",
   274  							},
   275  						},
   276  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   277  						Type:      "string",
   278  						Mandatory: false,
   279  						Aliases:   []config.Alias{},
   280  						Default:   os.Getenv("PIPER_containerRegistryUser"),
   281  					},
   282  					{
   283  						Name:        "host",
   284  						ResourceRef: []config.ResourceReference{},
   285  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   286  						Type:        "string",
   287  						Mandatory:   true,
   288  						Aliases:     []config.Alias{},
   289  						Default:     os.Getenv("PIPER_host"),
   290  					},
   291  					{
   292  						Name: "username",
   293  						ResourceRef: []config.ResourceReference{
   294  							{
   295  								Name:  "malwareScanCredentialsId",
   296  								Param: "username",
   297  								Type:  "secret",
   298  							},
   299  
   300  							{
   301  								Name:    "malwareScanUsernameVaultSecretName",
   302  								Type:    "vaultSecret",
   303  								Default: "malware-scan",
   304  							},
   305  						},
   306  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   307  						Type:      "string",
   308  						Mandatory: true,
   309  						Aliases:   []config.Alias{},
   310  						Default:   os.Getenv("PIPER_username"),
   311  					},
   312  					{
   313  						Name: "password",
   314  						ResourceRef: []config.ResourceReference{
   315  							{
   316  								Name:  "malwareScanCredentialsId",
   317  								Param: "password",
   318  								Type:  "secret",
   319  							},
   320  
   321  							{
   322  								Name:    "malwareScanPasswordVaultSecretName",
   323  								Type:    "vaultSecret",
   324  								Default: "malware-scan",
   325  							},
   326  						},
   327  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   328  						Type:      "string",
   329  						Mandatory: true,
   330  						Aliases:   []config.Alias{},
   331  						Default:   os.Getenv("PIPER_password"),
   332  					},
   333  					{
   334  						Name: "scanImage",
   335  						ResourceRef: []config.ResourceReference{
   336  							{
   337  								Name:  "commonPipelineEnvironment",
   338  								Param: "container/imageNameTag",
   339  							},
   340  						},
   341  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   342  						Type:      "string",
   343  						Mandatory: false,
   344  						Aliases:   []config.Alias{},
   345  						Default:   os.Getenv("PIPER_scanImage"),
   346  					},
   347  					{
   348  						Name:        "scanImageIncludeLayers",
   349  						ResourceRef: []config.ResourceReference{},
   350  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   351  						Type:        "bool",
   352  						Mandatory:   false,
   353  						Aliases:     []config.Alias{},
   354  						Default:     true,
   355  					},
   356  					{
   357  						Name: "scanImageRegistryUrl",
   358  						ResourceRef: []config.ResourceReference{
   359  							{
   360  								Name:  "commonPipelineEnvironment",
   361  								Param: "container/registryUrl",
   362  							},
   363  						},
   364  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   365  						Type:      "string",
   366  						Mandatory: false,
   367  						Aliases:   []config.Alias{},
   368  						Default:   os.Getenv("PIPER_scanImageRegistryUrl"),
   369  					},
   370  					{
   371  						Name:        "scanFile",
   372  						ResourceRef: []config.ResourceReference{},
   373  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   374  						Type:        "string",
   375  						Mandatory:   false,
   376  						Aliases:     []config.Alias{{Name: "file", Deprecated: true}},
   377  						Default:     os.Getenv("PIPER_scanFile"),
   378  					},
   379  					{
   380  						Name:        "timeout",
   381  						ResourceRef: []config.ResourceReference{},
   382  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   383  						Type:        "string",
   384  						Mandatory:   false,
   385  						Aliases:     []config.Alias{},
   386  						Default:     `600`,
   387  					},
   388  					{
   389  						Name:        "reportFileName",
   390  						ResourceRef: []config.ResourceReference{},
   391  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   392  						Type:        "string",
   393  						Mandatory:   false,
   394  						Aliases:     []config.Alias{},
   395  						Default:     `malwarescan_report.json`,
   396  					},
   397  				},
   398  			},
   399  			Outputs: config.StepOutputs{
   400  				Resources: []config.StepResources{
   401  					{
   402  						Name: "reports",
   403  						Type: "reports",
   404  						Parameters: []map[string]interface{}{
   405  							{"filePattern": "**/toolrun_malwarescan_*.json", "type": "malwarescan"},
   406  							{"type": "malwarescan"},
   407  						},
   408  					},
   409  				},
   410  			},
   411  		},
   412  	}
   413  	return theMetaData
   414  }