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